PDF -About the Tutorial - tutorialspointcom - Cfhipsterref Low Level Programming on Ios Mac Os
Wait Loading...

PDF :1

Like and share and download

Cfhipsterref Low Level Programming on Ios Mac Os

About the Tutorial - tutorialspointcom

Related PDF

About the Tutorial - tutorialspointcom


CFI Explanations of Yang Style Neigong

Foundation And Empire - Home Bqjwfgf Ebook

PDF Yang Imperial Style Taiji Ball Chinese Video Cd Cincincinchat client backend cincin io yang imperial style taiji ball chinese video cd pdf PDF Nei Gong bi brandhouse nei gong pdf PDF DOWNLOAD NEI GONGadmindev refocusapp nei gong pdf


Download Cfii Pts Wordpress PDF - LMO RH

PDF Flight Instructor PTS with changes 1 through 6 FAA faa gov training testing testing FAA S 8081 6D pdf PDF Flight Instructor Practical Test Standards for Rotorcraft FAA faa gov training

  1. flight instructor instrument pts
  2. faa pts
  3. cfi pts 2019
  4. flight instructor pts 2018
  5. cfi pts helicopter
  6. cfi lesson plans
  7. cfi acs
  8. atp pts helicopter


Text - SciencesPo SPIRE

PDF C&F CFI book Ä William Caspar Graustein Memorial Fund wcgmf pdf publication 17 pdf PDF FAA H 8083 9A Aviation Instructor's Handbook faa gov regulations policies FAA H 8083 9A pdf

  1. flight instructor lesson plan handbook pdf
  2. multi engine instructor lesson plans
  3. foi lesson plan
  4. how to make cfi lesson plans
  5. faa flight training handbook
  6. faa ground school book
  7. lesson plans for helicopter flight instructors pdf
  8. aviation pdf

CFIT (Culture Fair Intelligence Test) 3

International Journal O International Journal Of

PDF Test of “g” CULTURE FAIR Scale 3, Form A Shodhgangashodhganga inflibnet ac in jspui bitstream 21 appendix 203 pdf PDF APPENDIX N0 4 Answer key to culture Fair Intelligence Test, Scale shodhganga inflibnet ac in bitstream 10603 20 20

  1. culture fair intelligence test scale 3 pdf
  2. psychology today culture fair iq tests
  3. culture fair intelligence test scoring
  4. cattell culture fair standard deviation
  5. culture fair scale percentiles
  6. cfit test report
  7. norma cfit skala 3
  8. cattell iq test

Cfit - Dinda

kontribusi dimensi religiusitas terhadap - Digilib UIN SUKA

Aug 30, 2017 CFIT Cloud Forensic Investigator Toolkit – A Technology (CFIT), designed and developed as the outcome of the Dr Shrabani Dinda Jun 26, 2018 tu;fcl' CfiT Vcfl pernah putus tuk dinda, Teman sejatiku, Aul

  1. Dr Shrabani Dinda
  2. CfiT Vcfl
  3. q~41"'lCTII CfiT c:r
  4. Rabindra Nath Dinda
  5. pernah putus tuk dinda
  6. Adekku Dinda Novi Fitriana
  7. Role of Person-Organization Fit
  8. Dinda Niagara Ermaja
  9. CFit = Cash flow dari kegiatan
  10. model fit


Subject: GENERAL AVIATION Date: 4/1/03 AC No: 61-134

faa gov training testing training media cfit Controlled Flight Into Terrain Education and Training Aid U S Department of Transportation Federal Aviation Administration Flight Safety Foundation Introduction Message from the President of ICAO Disclaimer Volume 1 Section 1 4 Volume 2 Section 5 Index

CFM 56 - 5C Basic-Engine

CFM56-5B and - Civil Aviation Authority of New Zealand

PDF CFM56 5C Safran Aircraft Engines safran aircraft engines fiche cfm56 5c ang pdf PDF The CFM56 5C iasg co uk Entrance iasg co uk pdf s engine Pages 20from 20JULY

  1. cfm56-7b specifications
  2. 707 cfm56
  3. cfm engines
  4. cfm56 fuel consumption
  5. cfm engine failure
  6. cfm56 5b meaning
  7. cfm56 reliability
  8. cfm56 5b 7b

PDF Cfm56 3 Engine Manual Caroline Buttetwwg3 carolinebuttet ch cfm56 3 engine manual pdf PDF Cfm56 3 Engine Manual Kronoscode chap kronoscode cfm56 3 engine manual pdf PDF Cfm56 3 Engine Manualdev kofler it cfm56 3 engine

Cfm56 5b FDA

Code The Hidden Language Of Computer Hardware And Software

pottermckinney level c unit 12 answers pdf Answers, physical science grade 11 march question papers, Compaq Presario Cq40 Manual, Cfm56 5b Engine For Sale, Yamaha Pw80 Service Manual Download, holt spanish 1 answer key chapter, write personal experience paper, Accounts T S Grewal Solution 11 Class, Sharp El

Home back Next

Level Programming on Ios Mac Os


CFHipsterRef Low-Level Programming on iOS & Mac OS X

Table of Contents 1

Introduction 2

Kernel 3

Objective-C Runtime i

Message Sending iii

Metaprogramming with Properties iv

Associated Objects v

Dynamically Adding a Method vi

Method Swizzling vii

Dynamically Creating a Class 4

Clang i

Translation Units iii

Tokens v

Diagnostics vi

Fix-Its vii

Clang CLI viii

Static Analyzer 5

OSAtomic 6

Grand Central Dispatch 7

Inter-Process Communication 8

Core Services 9

ImageIO i

Supported Image Types ii

Writing to a File iii

Reading from a File iv

Incrementally Reading an Image v

Image Metadata 10

Accelerate i

Benchmarking Performance ii

Security i

Keychain Services ii

Cryptographic Message Syntax iii


Security Transform Services v

Randomization Services vi

CommonCrypto 12

System Configuration i

Determining Network Reachability Synchronously 2

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Determining Network Reachability Asynchronously 13

International Components for Unicode 14

Dictionary Services 15

Xcode Toolchain 16

Third-Party Tools 17


CFHipsterRef Low-Level Programming on iOS & Mac OS X

My Book Welcome in my book


CFHipsterRef Low-Level Programming on iOS & Mac OS X

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Objective-C Runtime

Objective-C Runtime

CFHipsterRef Low-Level Programming on iOS & Mac OS X

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Message Sending Consider the following Objective-C code:

The compiler will translate this into an equivalent objc_msgSend call:

Message Sending

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Metaprogramming with Properties #pragma mark

- NSCoding

objc_property_t *properties = class_copyPropertyList([self class],

i++) { objc_property_t property = properties[i]

NSString *key = [NSString stringWithUTF8String:property_getName(property)]

[self setValue:[decoder decodeObjectForKey:key] forKey:key]

objc_property_t *properties = class_copyPropertyList([self class],

i++) { objc_property_t property = properties[i]

NSString *key = [NSString stringWithUTF8String:property_getName(property)]

[coder encodeObject:[self valueForKey:key] forKey:key]

Metaprogramming with Properties

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Associated Objects objc_setAssociatedObject objc_getAssociatedObject objc_removeAssociatedObjects

Associated Objects

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Dynamically Adding a Method Class c'= [NSObject class]

IMP greetingIMP = imp_implementationWithBlock((NSString *)^(id self,

NSString *name){ return [NSString stringWithFormat:@"Hello,

const char *greetingTypes = [[NSString stringWithFormat:@"%s%s%s",

Dynamically Adding a Method

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Method Swizzling #import @implementation UIViewController (Tracking) + (void)load { static dispatch_once_t onceToken

SEL originalSelector = @selector(viewWillAppear:)

SEL swizzledSelector = @selector(xxx_viewWillAppear:)

Method originalMethod = class_getInstanceMethod(class,

Method swizzledMethod = class_getInstanceMethod(class,

// When swizzling a class method,

use the following: // Class class = object_getClass((id)self)

// Method originalMethod = class_getClassMethod(class,

// Method swizzledMethod = class_getClassMethod(class,

BOOL didAddMethod = class_addMethod(class,



if (didAddMethod) { class_replaceMethod(class,



} else { method_exchangeImplementations(originalMethod,

NSLog(@"viewWillAppear: %@",

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Swizzling should always be done in +load

There are two methods that are automatically invoked by the Objective-C runtime for each class

+load is sent when the class is initially loaded,

while +initialize is called just before the application calls its first method on that class or an instance of that class

Both are optional,

and are executed only if the method is implemented

Because method swizzling affects global state,

it is important to minimize the possibility of race conditions

+load is guaranteed to be loaded during class initialization,

which provides a modicum of consistency for changing system-wide behavior

By contrast,

+initialize provides no such guarantee of when it will be executed—in fact,

if that class is never messaged directly by the app

dispatch_once Swizzling should always be done in a dispatch_once

because swizzling changes global state,

we need to take every precaution available to us in the runtime

Atomicity is one such precaution,

as is a guarantee that code will be executed exactly once,

Grand Central Dispatch's dispatch_once provides both of these desirable behaviors,

and should be considered as much a standard practice for swizzling as they are for initializing singletons



& Implementations In Objective-C,

and implementations refer to particular aspects of the runtime,

although in normal conversation,

these terms are often used interchangeably to generally refer to the process of message sending

Here is how each is described in Apple's Objective-C Runtime Reference: 1

Selector (typedef struct objc_selector *SEL): Selectors are used to represent the name of a method at runtime

A method selector is a C string that has been registered (or "mapped") with the Objective-C runtime

Selectors generated by the compiler are automatically mapped by the runtime when the class is loaded

Method (typedef struct objc_method *Method): An opaque type that represents a method in a class definition

Implementation (typedef id (*IMP)(id,

)): This data type is a pointer to the start of the function that implements the method

This function uses standard C calling conventions as implemented for the current CPU architecture

The first argument is a pointer to self (that is,

the memory for the particular instance of this class,

The second argument is the method selector

The method arguments follow

Invoking _cmd It may appear that the following code will result in an infinite loop: Method Swizzling

CFHipsterRef Low-Level Programming on iOS & Mac OS X

NSLog(@"viewWillAppear: %@",

NSStringFromClass([self class]))


In the process of swizzling,

xxx_viewWillAppear: has been reassigned to the original implementation of UIViewController

It's good programmer instinct for calling a method on self in its own implementation to raise a red flag,

it makes sense if we remember what's really going on


if we were to call viewWillAppear: in this method,

it would cause an infinite loop,

since the implementation of this method will be swizzled to the viewWillAppear: selector at runtime

Method Swizzling

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Dynamically Creating a Class @interface Product : NSObject @property (readonly) NSString *name

@property (readonly) double price

a class is allocated with objc_allocateClassPair,

which specifies the class’s superclass and name

Class c'= objc_allocateClassPair([NSObject class],


After that,

instance variables are added to the class using class_addIvar

at fourth argument is used to determine the variable’s minimum alignment,

which depends on the ivar’s type and the target platform architecture

The next step is to define the implementation for the initializer,

with imp_implementationWithBlock:

To set name,

the call is simply object_setIvar

price is set by performing a memcpy at the previouslycalculated offset

Ivar nameIvar = class_getInstanceVariable(c,

ptrdiff_t priceIvarOffset = ivar_getOffset(class_getInstanceVariable(c,

IMP initIMP = imp_implementationWithBlock( ^(id self,

NSString *name,

double price) { object_setIvar(self,

char *ptr = ((char *)(__bridge void *)self) + priceIvarOffset

Dynamically Creating a Class

CFHipsterRef Low-Level Programming on iOS & Mac OS X

const char *initTypes = [[NSString stringWithFormat:@"%s%s%s%s%s%s",


Adding methods for the ivar getters follows much the same process

IMP nameIMP = imp_implementationWithBlock(^(id self) { return object_getIvar(self,

const char *nameTypes = [[NSString stringWithFormat:@"%s%s%s",

IMP priceIMP = imp_implementationWithBlock(^(id self) { char *ptr = ((char *)(__bridge void *)self) + priceIvarOffset

const char *priceTypes = [[NSString stringWithFormat:@"%s%s%s",


once all of the methods are added,

the class is registered with the runtime

And from that point on,

Product can be interacted with in Objective-C like any other class:

Product *widget = [[Product alloc] initWithName:@"Widget" price:50

NSLog(@"%@: %g",

Dynamically Creating a Class

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Clang 传统的编译器通常分为三个部分,前端(frontEnd),优化器(Optimizer)和后端(backEnd)。在编译过程中: 1

前端主要负责词法和语法分析,将源代码转化为抽象语法树; 2

优化器则是在前端的基础上,对得到的中间代码进行优化,使代码更加高效; 3

后端则是将已经优化的中间代码转化为针对各自平台的机器代码。Clang则是以LLVM为后端的一款高 效易用,并且与IDE结合很好的编译前端。 先来看看 C 标准是怎么规定一个 C Compiler 在翻译过程中应该完成哪些步骤的(主要参考自ISO/IEC 9899(俗称C99)标准 "5

CFHipsterRef Low-Level Programming on iOS & Mac OS X

libclang libclang is the C interface to the Clang LLVM front-end

It’s a powerful way for C & Objective-C programs to introspect their own internal structure and composition

Clang Components libsupport

Basic support library,

System abstraction library,



SourceBuffer abstraction,

file system caching for input source files

Provides classes to represent the C AST,

and various helpers for analyzing and manipulating the AST (visitors,

Lexing and preprocessing,


is library invokes coarse-grained Actions provided by the client (e

libsema builds ASTs) but knows nothing about ASTs or other client-specific data structures

Semantic Analysis

is provides a set of parser actions to build a standardized AST for programs

Lower the AST to LLVM IR for optimization & code generation

Editing of text buffers (important for code rewriting transformation,

Static analysis support

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Translation Units The first step to working with source code is to load it into memory

Clang operates on translation units,

which are the ultimate form of C or Objective-C source code,

and any other preprocessor directives have been evaluated

A translation unit is created by passing a path to the source code file,

and any command-line compilation arguments:

CXIndex idx = clang_createIndex(0,

const char *filename = "path/to/Source

CXTranslationUnit tu = clang_parseTranslationUnit(idx,

CXTranslationUnit_ {

} clang_disposeTranslationUnit(tu)

Translation Units

CFHipsterRef Low-Level Programming on iOS & Mac OS X

AST In order to understand the structure of a translation unit,

Clang constructs an Abstract Syntax Tree (AST)

ASTs are the platonic ideal of what code,

derived by distilling constructs from their representation

CFHipsterRef Low-Level Programming on iOS & Mac OS X

ImageIO Image I/O is a powerful,

albeit lesser-known framework for working with images

Independent of Core Graphics,

it can read and write between between many different formats,

and perform common image processing operations

e framework offers the fastest image encoders and decoders on the platform,

with advanced caching mechanisms and even the ability to load images incrementally


CFHipsterRef Low-Level Programming on iOS & Mac OS X

Supported Image Types According to the official docs,

Image I/O supports "most image formats"

Rather than take the docs at their word and guess what exactly that entails,

this information can be retrieved programmatically

CGImageSourceCopyTypeIdentifiers returns list of UTIs for image types supported:

Supported Image Types

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Writing to a File UIImage *image =

NSURL *fileURL = [NSURL fileURLWithPath:@"/path/to/output

NSString *UTI = @"public

NSDictionary *options = @{ (__bridge id) kCGImageDestinationLossyCompressionQuality: @(0

(__bridge id)kCGImagePropertyOrientation: @(4),

(__bridge id)kCGImagePropertyHasAlpha: @(NO) }

CGImageDestinationRef imageDestinationRef = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL,

CGImageDestinationAddImage(imageDestinationRef,[imageCGImage],(__bridge CFDictionaryRef)options)



Writing to a File

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Reading from a File NSURL *fileURL = [NSURL fileURLWithPath:@"/path/to/input

NSDictionary *options = @{ (__bridge id)kCGImageSourceTypeIdentifierHint: @"{public

(__bridge id)kCGImageSourceShouldCache: @(YES),

(__bridge id)kCGImageSourceShouldAllowFloat: @(YES),

CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((__bridge CFURLRef)fileURL,

CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef,

(__bridge CFDictionaryRef)options)

UIImage *image = [UIImage imageWithCGImage:imageRef]



Reading from a File

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Incrementally Reading an Image

mutableResponseData appendData:data]


mutableResponseData length] [dataTask countOfBytesExpectedToReceive])

CGSizeZero)) { NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(self

if (properties) { NSNumber *width = properties[(__bridge id)kCGImagePropertyPixelWidth]

NSNumber *height = properties[(__bridge id)kCGImagePropertyPixelHeight]

imageSize = CGSizeMake([width floatValue],

} } } CGImageRef imageRef = CGImageSourceCreateImageAtIndex(self

UIImage *image = [UIImage imageWithCGImage:imageRef]



^{ // delete or block callback to update with image })

Incrementally Reading an Image

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Image Metadata Metadata is divided into several different dictionaries,

which can be specified with any of the following keys: kCGImagePropertyTIFFDictionary kCGImagePropertyGIFDictionary kCGImagePropertyJFIFDictionary kCGImagePropertyExifDictionary kCGImagePropertyPNGDictionary kCGImagePropertyIPTCDictionary kCGImagePropertyGPSDictionary kCGImagePropertyRawDictionary kCGImagePropertyCIFFDictionary kCGImageProperty8BIMDictionary kCGImagePropertyDNGDictionary kCGImagePropertyExifAuxDictionary

NSDictionary *properties = (__bridge_transfer NSDictionary *)CGImageSourceCopyPropertiesAtIndex(self

NSDictionary *EXIF = properties[(__bridge id)kCGImagePropertyExifDictionary]

if (EXIF) { NSString *Fnumber = EXIF[(__bridge id)kCGImagePropertyExifFNumber]

NSString *exposure = EXIF[(__bridge id)kCGImagePropertyExifExposureTime]

NSString *ISO = EXIF[(__bridge id)kCGImagePropertyExifISOSpeedRatings]

NSLog(@"Shot Information: %@ %@ %@",


} NSDictionary *GPS = properties[(__bridge id)kCGImagePropertyGPSDictionary]

if (GPS) { NSString *latitude = GPS[(__bridge id)kCGImagePropertyGPSLatitude]

NSString *latitudeRef = GPS[(__bridge id)kCGImagePropertyGPSLatitudeRef]

NSString *longitude = GPS[(__bridge id)kCGImagePropertyGPSLongitude]

NSString *longitudeRef = GPS[(__bridge id)kCGImagePropertyGPSLongitudeRef]

NSLog(@"GPS: %@ %@ / %@ %@",

Image Metadata

CFHipsterRef Low-Level Programming on iOS & Mac OS X



CFHipsterRef Low-Level Programming on iOS & Mac OS X

Benchmarking Performance 1

Populating an Array

NSUInteger count = 10000000

float *array = malloc(count * sizeof(float))

Multiplying an Array

Summing an Array

float sum = cblas_sasum(count,


i++) { array[i] = (float)arc4random()

Benchmarking Performance

CFHipsterRef Low-Level Programming on iOS & Mac OS X

{ if (array[i] > array[maxLocation]) { maxLocation = i

NSUInteger maxLocation = cblas_isamax(count,

Benchmarking Performance

CFHipsterRef Low-Level Programming on iOS & Mac OS X

vecLib vecLib is comprised of the following 9 headers:

Interface for BLAS functions

Interface for LAPACK functions

Vector implementations of the BLAS routines


Basic algebraic operations

saturated addition / subtraction,

Transcendental operations (sin,

) on single vector floating point quantities

Transcendental operations on arrays of floating point quantities


Operations on large numbers (128-,

Digital signal processing algorithms including FFTs,

h Fast-Fourier Transform (FFT) is the fundamental digital signal processing algorithm

It decomposes a sequence of values into components with different frequencies

Although they have wide-ranging applications across mathematics and engineering,

most application developers encounter FFTs for audio or video processing,

as a way of determining the critical values in a noisy signal

int log2_x = (int)log2((double)x)

int log2_y = (int)log2((double)y)

DSPComplex *data = (DSPComplex *)malloc(sizeof(DSPComplex) * dimensions)

realp = (float *)malloc(sizeof(float) * dimensions),

imagp = (float *)malloc(sizeof(float) * dimensions),

FFTSetup weights = vDSP_create_fftsetup(fmax(log2_x,



CFHipsterRef Low-Level Programming on iOS & Mac OS X


CFHipsterRef Low-Level Programming on iOS & Mac OS X

vImage vImage is comprised of 6 headers:

Alpha compositing functions


Converting between image format (e

Planar8 to PlanarF,

ARGB8888 to Planar8)


Image convolution routines (e


Geometric transformations (e


Functions for calculating image histograms and image normalization


Image morphology procedures (e


Image transformation operations (e

h Alpha compositing is a process of combining multiple images according to their alpha components

For each pixel in an image,

value is used to determine how much of the image underneath it will be shown

vImage functions are available for blending or clipping

The most common operation is compositing a top image onto a bottom image:

UIImage *topImage,

CGImageRef topImageRef = [topImage CGImage]

CGImageRef bottomImageRef = [bottomImage CGImage]

CGDataProviderRef topProvider = CGImageGetDataProvider(topImageRef)

CFDataRef topBitmapData = CGDataProviderCopyData(topProvider)

size_t width = CGImageGetWidth(topImageRef)

size_t height = CGImageGetHeight(topImageRef)

size_t bytesPerRow = CGImageGetBytesPerRow(topImageRef)

data = (void *)CFDataGetBytePtr(topBitmapData),

CGDataProviderRef bottomProvider = CGImageGetDataProvider(bottomImageRef)

CFDataRef bottomBitmapData = CGDataProviderCopyData(bottomProvider)

vImage_Buffer bottomBuffer = {

data = (void *)CFDataGetBytePtr(bottomBitmapData),

CFHipsterRef Low-Level Programming on iOS & Mac OS X

void *outBytes = malloc(height * bytesPerRow)

vImage_Error error = vImagePremultipliedAlphaBlend_ARGB8888(&topBuffer,

kv if (error) { NSLog(@"Error: %ld",


CGImageRef imageRef = [image CGImage]

size_t width = CGImageGetWidth(imageRef)

size_t height = CGImageGetHeight(imageRef)

size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef)

size_t bytesPerRow = CGImageGetBytesPerRow(imageRef)

CGDataProviderRef sourceImageDataProvider = CGImageGetDataProvider(imageRef)

CFDataRef sourceImageData = CGDataProviderCopyData(sourceImageDataProvider)

vImage_Buffer sourceImageBuffer = {

data = (void *)CFDataGetBytePtr(sourceImageData),

uint8_t *destinationBuffer = malloc(CFDataGetLength(sourceImageData))

vImage_Buffer destinationImageBuffer = {

const uint8_t channels[4] = {0,

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB()

CGContextRef destinationContext = CGBitmapContextCreateWithData(destinationBuffer,

kCGBitmapByteOrderDefault | kCGImageAlphaPremul NULL)

CGImageRef permutedImageRef = CGBitmapContextCreateImage(destinationContext)

UIImage *permutedImage = [UIImage imageWithCGImage:permutedImageRef]



CFHipsterRef Low-Level Programming on iOS & Mac OS X



h Image convolution is the process of multiplying each pixel and its adjacent pixels by a kernel,

or square matrix with a sum of 1

Depending on the kernel,

a convolution operation can either blur,

Except for specific situations where a custom kernel is required,

convolution operations would be betterserved by the Core Image framework,


for a straightforward CPU-based solution,

vImage delivers: Blurring an Image

UIImage *inImage =

CGImageRef inImageRef = [inImage CGImage]

CGDataProviderRef inProvider = CGImageGetDataProvider(inImageRef)

CFDataRef inBitmapData = CGDataProviderCopyData(inProvider)

data = (void *)CFDataGetBytePtr(inBitmapData),

width = CGImageGetWidth(inImageRef),

height = CGImageGetHeight(inImageRef),

rowBytes = CGImageGetBytesPerRow(inImageRef),

void *outBytes = malloc(CGImageGetBytesPerRow(inImageRef) * CGImageGetHeight(inImageRef))

// Size of convolution vImage_Error error = vImageBoxConvolve_ARGB8888(&inBuffer,

if (error) { NSLog(@"Error: %ld",

} CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB()

CGContextRef c'= CGBitmapContextCreate(outBuffer

CFHipsterRef Low-Level Programming on iOS & Mac OS X


CGImageRef outImageRef = CGBitmapContextCreateImage(c)

UIImage *outImage = [UIImage imageWithCGImage:outImageRef]






h Resizing an image is another operation that is perhaps more suited for another,

GPU-based framework,

For a given vImage buffer,

it might be more performant to scale with Accelerate using vImageScale_* rather than convert back and forth between a CGImageRef: Resizing an Image

void *outBytes = malloc(trunc(inBuffer

height * scaleFactor) * inBuffer

vImage_Error error = vImageScale_ARGB8888(&inBuffer,

if (error) { NSLog(@"Error: %ld",


h Detecting if an Image Has Transparency

UIImage *image

CGImageRef imageRef = [image CGImage]

CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef)

CFDataRef bitmapData = CGDataProvi vImagePixelCount a[256],

vImagePixelCount *histogram[4] = {a,

CFHipsterRef Low-Level Programming on iOS & Mac OS X

vImage_Buffer buffer = {

data = (void *)CFDataGetBytePtr(bitmapData),

width = CGImageGetWidth(imageRef),

height = CGImageGetHeight(imageRef),

rowBytes = CGImageGetBytesPerRow(imageRef),

vImage_Error error = vImageHistogramCalculation_ARGB8888(&buffer,

if (error) { NSLog(@"Error: %ld",

i++) { hasTransparency = histogram[3][i] == 0

} CGDataProviderRelease(dataProvider)



size_t bytesPerRow = CGImageGetBytesPerRow([image CGImage])

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB()

CGContextRef sourceContext = CGBitmapContextCreate(NULL,

kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst)



void *sourceData = CGBitmapContextGetData(sourceContext)

vImage_Buffer sourceBuffer = {

size_t length = height * bytesPerRow

void *destinationData = malloc(length)

vImage_Buffer destinationBuffer = {

CFHipsterRef Low-Level Programming on iOS & Mac OS X

static unsigned char kernel[9] = { 1,


CGContextRef destinationContext = CGBitmapContextCreateWithData(destinationData,

kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst,

CGImageRef dilatedImageRef = CGBitmapContextCreateImage(destinationContext)

UIImage *dilatedImage = [UIImage imageWithCGImage:dilatedImageRef]





CFHipsterRef Low-Level Programming on iOS & Mac OS X

Security The Security framework can be divided up into Keychain Services,

Cryptographic Message Syntax,

Security Transform Services,


CFHipsterRef Low-Level Programming on iOS & Mac OS X

Keychain Services Keychain is the password management system on iOS & OS X

It stores certificates and private keys,

as well as passwords for websites,

Interactions with the Keychain are mediated through queries,

rather than direct manipulation

The queries themselves can be quite complicated,

A query is a dictionary consisting of the following components: The class of item to search for,

"Internet Password",


The return type for the query,



One or more attribute key-value pairs to match on

One or more search key-value pairs to further refine the results,

such as whether to match strings with case sensitivity,

only match trusted certificates,

or limit to just one result or return all

Getting Keychain Items

NSString *service = @"com

NSString *account = @"username"

NSDictionary *query = @{ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,

(__bridge id)kSecAttrService: serv (__bridge id)kSecAttrAccount: key,

(__bridge id)kSecMatchLimit: kSecMatchLimitOne,

CFTypeRef result

OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query,

In this example,

the query tells the keychain to find all generic password items for the service com

app with the matching username

kSecAttrService defines the scope of credentials,

while kSecAttrAccount acts as a unique identifier

e search option kSecMatchLimitOne is passed to ensure that only the first match is returned,

If status is equal to errSecSuccess (0),

then result should be populated with the matching credential

Adding and Updating Keychain Items NSData *data =

Keychain Services

CFHipsterRef Low-Level Programming on iOS & Mac OS X

{ NSDictionary *updatedAttributes = @{(__bridge id)kSecValueData: data}

SecItemUpdate((__bridge CFDictionaryRef)query,

(__bridge CFDictionaryRef)updatedAttributes)

} else { NSMutableDictionary *attributes = [query mutableCopy]

attributes[(__bridge id)kSecValueData] = data

attributes[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleAfterFirstUnlock

SecItemAdd((__bridge CFDictionaryRef)attributes,

Keychain Services

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Cryptographic Message Syntax Cryptographic Message Syntax is the IETF’s standard for public key encryption and digital signatures for S/MIME messages

Apple’s Cryptographic Message Syntax Services in the Security framework provide APIs that implement these industry standard algorithms

Messages can either be signed,

by any number of signers or recipients

To sign a message is to allow the recipient to verify its sender

To encrypt a message is to ensure that it kept secret from everyone but the recipients,

who alone are able to decrypt the message’s content

These two operations are orthogonal,

Encoding a Message

NSData *data

SecCertificateRef certificateRef

CMSEncoderRef encoder


// Encrypt CMSEncoderUpdateContent(encoder,


// Sign SecIdentityRef identityRef = nil








CFDataRef encryptedDataRef


NSData *encryptedData = [NSData dataWithData:(__bridge NSData *)encryptedDataRef]


Decoding a Message

CMSDecoderRef decoder




CFDataRef decryptedDataRef


NSData *decryptedData = [NSData dataWithData:(__bridge NSData *)decryptedDataRef]



Cryptographic Message Syntax

CFHipsterRef Low-Level Programming on iOS & Mac OS X


Scanning through the plain text output,

several pieces of information come to the surface: Certificate issuer Validity period Certificate holder Public key of the owner Digital signature from the certification authority Certificates are the basis for the cryptographic infrastructure used to secure the internet

One of the most common interactions an iOS or OS X developer has certificates is an authentication challenge from a URL request:

NSURLAuthenticationChallenge *challenge =

SecTrustRef trust = challenge

SecPolicyRef X509Policy = SecPolicyCreateBasicX509()


(__bridge CFArrayRef)@[(__bridge id)X509Policy])

SecTrustResultType result



CFHipsterRef Low-Level Programming on iOS & Mac OS X

Security Transform Services Base64 Encoding

SecTransformRef transform = SecEncodeTransformCreate(kSecBase64Encoding,



NSData *encodedData = (__bridge_transfer NSData *)SecTransformExecute(transform,


Base64 Decoding

SecTransformRef transform = SecEncodeTransformCreate(kSecBase64Decoding,

NSData *decodedData = (__bridge_transfer NSData *)SecTransformExecute(transform,


Security Transform Services

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Randomization Services Cryptography is predicated on unpredictable,

Without such a guarantee,

it’s all just security theater

SecRandomCopyBytes reads from /dev/random,

which generates cryptographicallysecure random bytes

/dev/random is a special file on Unix systems that streams entropy based on the environmental noise of the device

NSUInteger length = 1024

NSMutableData *mutableData = [NSMutableData dataWithLength:length]

OSStatus success = SecRandomCopyBytes(kSecRandomDefault,

Randomization Services

CFHipsterRef Low-Level Programming on iOS & Mac OS X

CommonCrypto Digests To calculate a checksum in code,

NSData *data =

uint8_t output[CC_SHA1_DIGEST_LENGTH]


NSData *digest = [NSData dataWithBytes:output length:CC_SHA1_DIGEST_LENGTH]

HMAC NSData *data,

unsigned int length = CC_SHA1_DIGEST_LENGTH


Symmetric Encryption 1

The first step is to create a function that generates a PBKDF2 key from a salted password

A salt is random data used as an additional input to a one-way function performed on a password

static NSData * AES128PBKDF2KeyWithPassword(NSString *password,

NSData *salt,

NSError * __autoreleasing *error) { NSCParameterAssert(password)


NSMutableData *mutableDerivedKey = [NSMutableData dataWithLength:kCCKeySizeAES128]

CCCryptorStatusstatus = CCKeyDerivationPBKDF(kCCPBKDF2,



[mutableDerivedKey mutableBytes],


NSData *derivedKey = nil


CFHipsterRef Low-Level Programming on iOS & Mac OS X

} } else { derivedKey = [NSData dataWithData:mutableDerivedKey]

a function to encrypt the data can be created,

which takes the data to encrypt and password,

and returns the generated salt and initialization,

as well as any error encountered in performing the operation,

static NSData * AES128EncryptedDataWithData(NSData *data,

NSString *password,

NSData * __autoreleasing *salt,

NSData * __autoreleasing *initializationVector,

NSError * __autoreleasing *error) { NSCParameterAssert(initializationVector)


uint8_t *saltBuffer = malloc(8)


NSData *key = AES128PBKDF2KeyWithPassword(password,

uint8_t *initializationVectorBuffer = malloc(kCCBlockSizeAES128)


size_t numberOfBytesEncrypted = 0

CCCryptorStatusstatus = CCCrypt(kCCEncrypt,



NSData *encryptedData = nil

!= kCCSuccess) { if (error) { *error = [[NSError alloc] initWithDomain:nil code:status userInfo:nil]


CFHipsterRef Low-Level Programming on iOS & Mac OS X

} else { encryptedData = [[NSData alloc] initWithBytes:buffer length:numberOfBytesEncrypted]


do the same process in reverse,

this time passing the data and password along with the salt and initialization vector generated from the encryption function:


NSData *salt,

NSData *ini { NSData *key = AES128PBKDF2KeyWithPassword(password,

size_t size = [data length] + kCCBlockSizeAES128

size_t numberOfBytesDecrypted = 0

CCCryptorStatusstatus = CCCrypt(kCCDecrypt,



NSData *encryptedData = nil

!= kCCSuccess) { if (error) { *error = [[NSError alloc] initWithDomain:nil code:status userInfo: nil]

} } else { encryptedData = [[NSData alloc] initWithBytes:buffer length:numberOfBytesDecrypted]


CFHipsterRef Low-Level Programming on iOS & Mac OS X

Determining Network Reachability Synchronously Like any networking,

establishing reachability should not be done synchronously

SCNetworkReachabilityRef networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefaul [@"www

SCNetworkReachabilityFlags flags = SCNetworkReachabilityGetFlags(networkReachability,

// Use flags to determine reachability CFRelease(networkReachability)

SCNetworkReachabilityRef is the data type responsible for determining network reachability

It can be created by either passing host name,

BOOL ignoresAdHocWiFi = NO

s_addr = htonl(ignoresAdHocWiFi


SCNetworkReachabilityRef networkReachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDef

BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable)

BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired)

BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand )

!= 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)

BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)

BOOL isNetworkReachable = (isReachable && (

!needsConnection || canConnectWithoutUserInteraction))

if (isNetworkReachable == NO) { // Not Reachable } #if TARGET_OS_IPHONE

Determining Network Reachability Synchronously

CFHipsterRef Low-Level Programming on iOS & Mac OS X

else if ((flags & kSCNetworkReachabilityFlagsIsWWAN)

!= 0) { // Reachable via WWAN } #endif else { // Reachable via WiFi }

Calling SCNetworkReachabilityFlags on the main thread invokes a DNS lookup with a 30 second timeout

This is bad

Don’t make blocking,

synchronous calls to SCNetworkReachabilityFlags

Determining Network Reachability Synchronously

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Determining Network Reachability Asynchronously Thankfully,

the System Configuration framework provides a set of APIs for monitoring reachability changes asynchronously

static void ReachabilityCallback( SCNetworkReachabilityRef target,

SCNetworkConnectionFlags flags,

SCNetworkReachabilityContext context = {0,






Determining Network Reachability Asynchronously

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Xcode Toolchain Xcode Tools 1

This will install the Command Line Tools,

which are necessary for compiling Objective-C code

xcrun xcrun is the fundamental Xcode command line tool

With it,

In addition to running commands,

xcrun can find binaries and show the path to an SDK:

Because xcrun executes in the context of the active Xcode version (as set by xcode-select),

it is easy to have multiple versions of the Xcode toolchain co-exist on a single system

Using xcrun in scripts and other external tools has the advantage of ensuring consistency across different environments

For example,

Xcode ships with a custom distribution of Git

By invoking $ xcrun git rather than just $ git ,

a build system can guarantee that the correct distribution is run

xcodebuild Without passing any build settings,

xcodebuild defaults to the scheme and configuration most recently used by Xcode

and derived data location can be configured:

There are six build actions that can be invoked in sequence: build analyze archive archive installsrc install clean

CFHipsterRef Low-Level Programming on iOS & Mac OS X

The genstrings utility generates a

strings file from the specified C or Objective-C source files

strings file is used for localizing an application in different locales,

as described under "Internationalization" in Apple’s Cocoa Core Competencies

For each use of the NSLocalizedString macro in a source file,

genstrings will append the key and comment into the target file

It’s up to the developer to then create a copy of that file for each targeted locale and have that file translated

/* {User First Name}'s Profile */ "%@'s Profile"="profil de %[email protected]"

iprofiler iprofiler measure an app’s performance without launching Instruments

-o perf

xed This command simply opens Xcode

agvtool agvtool can be used to version Xcode projects,

by reading and writing the appropriate values in the Info

Compilation & Assembly clang: Compiles C,



and Objective-C programs nasm: Assembles files

symbols: Displays symbol information about a file or process

strip: Removes or modifies the symbol table attached to the output of the assembler and link editor

Xcode Toolchain

CFHipsterRef Low-Level Programming on iOS & Mac OS X

atos: Converts numeric addresses to symbols of binary images or processes

Processors unifdef: Removes conditional #ifdef macros from code

ifnames: Finds conditionals in C++ files

Libraries ld: Combines object files and libraries into a single file

otool: Displays specified parts of object files or libraries

libtool: Creates a library for use with the link editor,

ranlib: Updates the table of contents of archive libraries

lorder: Lists dependencies for object files

Scripting sdef: Scripting definition extractor

sdp: Scripting definition processor

desdp: Scripting definition generator

amlint: Checks Automator actions for problems

Packages installer: Installs OS X packages

pkgutil: Reads and manipulates OS X packages

Documentation headerdoc: Processes header documentation

gatherheaderdoc: Compiles and links headerdoc output

headerdoc2html: Generates HTML from headerdoc output

hdxml2manxml: Translates from headerdoc XML output to a file for use with xml2man xml2man: Converts Man Page Generation Language (MPGL) XML files into manual pages

Core Data momc: Compiles Managed Object Model (

mom) files mapc: Compiles Core Data Mapping Model (

Xcode Toolchain

CFHipsterRef Low-Level Programming on iOS & Mac OS X

Third-Party Tools appledoc In Objective-C,

the documentation tool of choice is appledoc 66

Using a Javadoc-like syntax,

appledoc is able to generate HTML and Xcode-compatible

h files that look nearly identical Apple’s official documentation

@param [param] [Description]: Describes what value should be passed or this parameter @return [Description]: Describes the return value of a method @see [selector]: Provide "see also" reference to related item @discussion [Discussion]: Provide additional background @warning [description]: Call out exceptional or potentially dangerous behavior To generate documentation,

execute the appledoc command within the root directory of an Xcode project,

passing metadata such as project and company name:

xctool xctool is a drop-in replacement for xcodebuild,

Every step of the build process is neatly organized and reported in a way that is understandable and visually appealing,

with ANSI colorization and a splash of Unicode ornamentation,

but xctool's beauty is not just skin-deep: build progress can also be reported in formats that can be read by other tools:

pretty: (default) a text-based reporter that uses ANSI colors and unicode symbols for pretty output

but with with no colors or Unicode

phabricator: outputs a JSON array of build/test results which can be fed into the Phabricator codereview tool

junit: produces a JUnit / xUnit compatible XML

Third-Party Tools

CFHipsterRef Low-Level Programming on iOS & Mac OS X

json-stream: a stream of build/test events as JSON dictionaries,

json-compilation-database: outputs a JSON Compilation Database of build events which can be used by Clang Tooling based tools,

OCLint OCLint is a static code analyzer that inspects C code for common sources of problems,

like empty if/else/try/catch/finally statements,unused local variables and parameters,

complicated code with high NCSS (Non Commenting Source Statements) or cyclomatic / NPath complexity,

json $ oclint-json-compilation-database

Nomad gem install nomad-cli

Cupertino Shenzhen Houston Venice Dubai

Third-Party Tools

CFHipsterRef Low-Level Programming on iOS & Mac OS X

CocoaPods Installing CocoaPods sudo gem install cocoapods

Managing Dependencies $ pod init $ pod 'X',

:commit => 'b4dc0ffee' $ pod install $ pod update

Trying Out a CocoaPod Creating a CocoaPod NSHipsterKit


summary = "A pretty obscure library

You've probably never heard of it

authors = { 'Mattt Thompson' => '[email protected]' } s

social_media_url = "https://twitter

source = { :git => 'https://github

source_files = 'NSHipsterKit' end

podspec file can be useful for organizing internal or private dependencies as well:

:path => 'path/to/directory/with/podspec'



CFHipsterRef Low-Level Programming on iOS & Mac OS X

Publishing a CocoaPod