Objective-C Cheat Sheet

From Notepedia
Jump to: navigation, search

Xcode Tips


CTRL + i


Pointers are declared like ordinary variables except they have an * in front of them to say they are a pointer

int x, *y;

Here, x is a scalar that contains integer values but y is a variable that contains memory addresses of integer variables

We can find the address of a variable by using the & operator

y = &x;

In the above, we have used the & operator to put the memory address of x into y and we say y is pointing to x

We can use pointers to read and change the contents of the variables they point to. This is done by using the dereferencing operator *

*y = 5;

Since we earlier set y to contain the address of x, setting *y to 5 sets x to 5   Similarly we can have

int z = *y;

This will set z equal to what x is since y points to x

It is easy to mishandle pointers. This will cause the program to crash

int *ptr;
*ptr = 6;	// 1.
ptr = 6;	// 2.
  1. ptr has not been set to point to any variable we have. The attempt to dereference it will cause the OS to crash the program.
  2. You are trying to set ptr to point to memory address 6. Since this memory address isn't allocated to your program, an attempt to dereference it will crash the program


Formatting Details at: https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Strings/Articles/formatSpecifiers.html

%c char
%d scalar (char, short, int, long)
%i signed int
%u unsigned scalar (char, short, int, long)
%f real
%lf double // printf only
%s C style string
%@ NSObject/NSString, ... (Cannot printf this)
%% Print %

How to Printf an NSString:

printf("%s : %s\n", [[exception name] UTF8String], [[exception reason] UTF8String]);

Checking Data Types

int isdigit(int c);


Get size of NSArray

int size = [array count];


Parse Char to NSString

char myChar = 'r';
NSString* string = [NSString stringWithFormat:@"%c" , myChar];

NSString manipulation

Append NSString to NSString

[nameOfNSString appendString:addNSString];

Append char to NSString

[nameOfNSString appendFormat:@"%c", nameOfChar];

Parse NSString to double

double var = [nsStringToParse doubleValue];

Parse NSString to float

float var = [contantString floatValue];

Print NSNumber as double

NSLog(@"%@", coordinate.latitude); //OR
NSLog(@"%f", coordinate.latitude.doubleValue);

Convert float to NSNumber

[calcData.argOperands addObject:[NSNumber numberWithDouble:var]];

Other NSString goodies http://borkware.com/quickies/one?topic=NSString

NSString to NSNumber http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:@"42"];

Append char to string

[operandString appendString:[NSString stringWithFormat:@"%c" , checkChar]];

Upper Limits of data types


INT_MAX 2147483647
INT_MIN -2147483648