From 4283f0c964f55295f024e535a2373ef8d04e4069 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:32:20 +0200 Subject: [FIX] filename --- objective-c.html.markdown | 99 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 objective-c.html.markdown (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown new file mode 100644 index 00000000..787a9219 --- /dev/null +++ b/objective-c.html.markdown @@ -0,0 +1,99 @@ +--- +language: Objectiv-C +author: Eugene Yagrushkin +author_url: www.about.me/yagrushkin +filename: learnc.Objectiv-C +--- + +Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. +It's is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. + +```Objective-C +// Single-line comments start with // + +/* +Multi-line comments look like this. +*/ + +##Basic types +// all the primitive variable types are the same as in C +// char, int, long, double, float + + +// Simple, common classes +// number +NSNumber *firstNumber = @1; +NSNumber *secondNumber = @23.0; +NSNumber *boolNumber = @YES; + +// string +NSString *aString = @"some string"; + +// array +NSArray *array = @[ @1, @2]; + +// dictionary +NSDictionay *dictionary = @{ @"aKey" : @"aValue", @"aKey2" : @"aValue2" }; + +// Import headers with #import +#import +#import "SomeAppDelegate.h" + +##Coding classes + +// Declare your class in a header(.h) file: + +@interface UserObject : NSObject{ +// instance variables +} + +// Class method + + (NSString*) ClassMethod; + +// Instance method + - (NSString*) instanceMethodWithParmeter:(NSString*)string; + +@end + +// Add class methods in an implementation (.m) file: + +@implementation UserObject + ++ (NSString*) ClassMethod{ + return @"SomeString"; +} + +- (NSString*) instanceMethodWithParmeter:(NSString*)string; +{ + return @"New string"; +} + +- (NSString*) otherMethodWithString:(NSString*)string; +{ + return [NSString stringWithString:string]; +} +@end + +// Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. +UserObject *someObject = [[UserObject alloc] init]; + +##Calling Methods + +// The Objective-C model of object-oriented programming is based on message passing to object instances. +// In Objective-C one does not simply call a method; one sends a message. + +[someObject instanceMethodWithParmeter:@"Steve Jobs"]; + +##Nested Messages +// nested messages look like this: + +[someObject instanceMethodWithParmeter:[someObject otherMethodWithString:@"Jony Ive"]]; + +``` +## Further Reading + +[Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + +[Objectively Speaking: A Crash Course in Objective-C](http://www.raywenderlich.com/12444/objectively-speaking-a-crash-course-in-objective-c) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 5b182eb5e99be7d04071cdb04466ccdae7b2fde9 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:38:39 +0200 Subject: [UPDATE] Authors --- objective-c.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 787a9219..df789677 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -1,8 +1,11 @@ --- -language: Objectiv-C -author: Eugene Yagrushkin -author_url: www.about.me/yagrushkin -filename: learnc.Objectiv-C + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +filename: LearnObjectiveC.m + --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. -- cgit v1.2.3 From d842eb4f819568c1503c26e494e271f1cd179542 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:45:49 +0200 Subject: minor fixes --- objective-c.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index df789677..21460632 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -8,8 +8,8 @@ filename: LearnObjectiveC.m --- -Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch. -It's is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. +Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. +It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. ```Objective-C // Single-line comments start with // @@ -97,6 +97,6 @@ UserObject *someObject = [[UserObject alloc] init]; [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) -[Objectively Speaking: A Crash Course in Objective-C](http://www.raywenderlich.com/12444/objectively-speaking-a-crash-course-in-objective-c) +[Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 48fcef441fce2235e5dcd0d7c052b44f315504a5 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 14:56:09 +0200 Subject: [ADD] Hello World! --- objective-c.html.markdown | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 21460632..63aa64f1 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -18,7 +18,26 @@ It is a general-purpose, object-oriented programming language that adds Smalltal Multi-line comments look like this. */ -##Basic types +// Imports the Foundation headers with #import +#import + +// Your program's entry point is a function called +// main with an integer return type. +int main (int argc, const char * argv[]) +{ + // Create an autorelease pool to manage the memory into your program + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + // Print "Hello World!" to the console + NSLog(@"Hello World!"); + + // Clean up the memory you used into your program + [pool drain]; + + // End your program + return 0; +} + // all the primitive variable types are the same as in C // char, int, long, double, float -- cgit v1.2.3 From a29c4ee753894d1b58fa398d9f49567d098d6221 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 15:25:47 +0200 Subject: [Refactoring] Literals --- objective-c.html.markdown | 80 ++++++++++++++++++++++++++--------------------- 1 file changed, 44 insertions(+), 36 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 63aa64f1..2b8e9874 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -28,72 +28,80 @@ int main (int argc, const char * argv[]) // Create an autorelease pool to manage the memory into your program NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - // Print "Hello World!" to the console - NSLog(@"Hello World!"); + // Use NSLog to print lines to the console + NSLog(@"Hello World!"); // Print "Hello World!" - // Clean up the memory you used into your program - [pool drain]; - - // End your program - return 0; -} + // character literals + NSNumber *theLetterZ = @'Z'; -// all the primitive variable types are the same as in C -// char, int, long, double, float + // integral literals + NSNumber *fortyTwo = @42; + NSNumber *fortyTwoUnsigned = @42U; + NSNumber *fortyTwoLong = @42L; + NSNumber *fortyTwoLongLong = @42LL; + // floating point literals + NSNumber *piFloat = @3.141592654F; + NSNumber *piDouble = @3.1415926535; -// Simple, common classes -// number -NSNumber *firstNumber = @1; -NSNumber *secondNumber = @23.0; -NSNumber *boolNumber = @YES; + // BOOL literals + NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES] + NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO] -// string -NSString *aString = @"some string"; + // strings + NSString *helloString = @"hello"; -// array -NSArray *array = @[ @1, @2]; + // array + NSArray *anArray = @[@1, @2]; -// dictionary -NSDictionay *dictionary = @{ @"aKey" : @"aValue", @"aKey2" : @"aValue2" }; + // dictionary + NSDictionay *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; -// Import headers with #import -#import -#import "SomeAppDelegate.h" + // Clean up the memory you used into your program + [pool drain]; + + // End your program + return 0; +} -##Coding classes +/////////////////////////////////////// +// Classes And Functions +/////////////////////////////////////// // Declare your class in a header(.h) file: -@interface UserObject : NSObject{ -// instance variables +@interface UserObject : NSObject +{ + // instance variables } // Class method - + (NSString*) ClassMethod; ++ (NSString *)classMethod; // Instance method - - (NSString*) instanceMethodWithParmeter:(NSString*)string; +- (NSString *)instanceMethodWithParmeter:(NSString *)string; @end -// Add class methods in an implementation (.m) file: +// Implement the methods in an implementation (.m) file: @implementation UserObject -+ (NSString*) ClassMethod{ - return @"SomeString"; ++ (NSString *)classMethod +{ + return @"SomeString"; } -- (NSString*) instanceMethodWithParmeter:(NSString*)string; +- (NSString *)instanceMethodWithParmeter:(NSString *)string { - return @"New string"; + return @"New string"; } -- (NSString*) otherMethodWithString:(NSString*)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number { - return [NSString stringWithString:string]; + return @42; } + @end // Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. -- cgit v1.2.3 From 0bd403fdb935331c3c391ffd79f0245032dee3b5 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 15:50:09 +0200 Subject: [UPDATE] Literals Examples --- objective-c.html.markdown | 63 ++++++++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 22 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 2b8e9874..284eca92 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -29,33 +29,52 @@ int main (int argc, const char * argv[]) NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Use NSLog to print lines to the console - NSLog(@"Hello World!"); // Print "Hello World!" + NSLog(@"Hello World!"); // Print the string "Hello World!" - // character literals + // String object + NSString *worldString = @"World"; + // %@ is an object + NSLog(@"Hello %@!", worldString); // Print "Hello World!" + + // Character literals NSNumber *theLetterZ = @'Z'; + NSLog(@"%c", [theLetterZ charValue]); - // integral literals - NSNumber *fortyTwo = @42; - NSNumber *fortyTwoUnsigned = @42U; - NSNumber *fortyTwoLong = @42L; - NSNumber *fortyTwoLongLong = @42LL; - - // floating point literals - NSNumber *piFloat = @3.141592654F; - NSNumber *piDouble = @3.1415926535; + // Integral literals + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwo intValue]; + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsigned unsignedIntValue]; + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [aLong longValue]; + NSLog(@"%li", fortyTwoLong); + + // Floating point literals + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloat floatValue]; + NSLog(@"%f", piFloat); + + NSNumber *piDoubleNumber = @3.1415926535; + piDouble = [piDouble doubleValue]; + NSLog(@"%f", piDouble); // BOOL literals - NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES] - NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO] - - // strings - NSString *helloString = @"hello"; - - // array - NSArray *anArray = @[@1, @2]; - - // dictionary - NSDictionay *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + + // Array object + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdObject); // Print "Third number = 3" + + // Dictionary object + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // Print "Object = (null)" // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 947c137680c2699bdb118b63460c560bac1fdd3c Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 15:52:11 +0200 Subject: minor fixes --- objective-c.html.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 284eca92..fc4b2900 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -37,29 +37,30 @@ int main (int argc, const char * argv[]) NSLog(@"Hello %@!", worldString); // Print "Hello World!" // Character literals - NSNumber *theLetterZ = @'Z'; - NSLog(@"%c", [theLetterZ charValue]); + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; + NSLog(@"%c", theLetterZ); // Integral literals NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwo intValue]; + int fortyTwo = [fortyTwoNumber intValue]; NSLog(@"%i", fortyTwo); NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsigned unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [aLong longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; NSLog(@"%li", fortyTwoLong); // Floating point literals NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloat floatValue]; + float piFloat = [piFloatNumber floatValue]; NSLog(@"%f", piFloat); NSNumber *piDoubleNumber = @3.1415926535; - piDouble = [piDouble doubleValue]; + piDouble = [piDoubleNumber doubleValue]; NSLog(@"%f", piDouble); // BOOL literals -- cgit v1.2.3 From 0040ce616b4e27a182834cd2fd03aacc2561a198 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:04:20 +0200 Subject: [UPDATE] Object Declaration --- objective-c.html.markdown | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index fc4b2900..c3df514b 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -25,15 +25,28 @@ Multi-line comments look like this. // main with an integer return type. int main (int argc, const char * argv[]) { - // Create an autorelease pool to manage the memory into your program + // Create an autorelease pool to manage the memory into the program NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" - // String object - NSString *worldString = @"World"; + /////////////////////////////////////// + // Types & Variables + /////////////////////////////////////// + + // Primitive declarations + int myPrimitive; + + // Object declarations + // Put the * in front of the variable names for strongly-typed object declarations + MyClass *myObject1; // Strong typing + id myObject2; // Weak typing // %@ is an object + NSLog(@"%@ and %@", myObject1, myObject2); // Print "(null) and (null)" + + // String + NSString *worldString = @"World"; NSLog(@"Hello %@!", worldString); // Print "Hello World!" // Character literals @@ -50,6 +63,10 @@ int main (int argc, const char * argv[]) unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; NSLog(@"%u", fortyTwoUnsigned); + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; + NSLog(@"%hi", fortyTwoShort); + NSNumber *fortyTwoLongNumber = @42L; long fortyTwoLong = [fortyTwoLongNumber longValue]; NSLog(@"%li", fortyTwoLong); @@ -77,10 +94,14 @@ int main (int argc, const char * argv[]) NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + // Clean up the memory you used into your program [pool drain]; - // End your program + // End the program return 0; } -- cgit v1.2.3 From 25f4c7e80a4682db35daed75d42ca91eb1504736 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:07:58 +0200 Subject: minor fixes --- objective-c.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index c3df514b..ad2bedf9 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -36,14 +36,16 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Primitive declarations - int myPrimitive; + int myPrimitive1; + long myPrimitive2; // Object declarations // Put the * in front of the variable names for strongly-typed object declarations MyClass *myObject1; // Strong typing id myObject2; // Weak typing // %@ is an object - NSLog(@"%@ and %@", myObject1, myObject2); // Print "(null) and (null)" + // 'description' is a convention to display the value of the Objects + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" // String NSString *worldString = @"World"; -- cgit v1.2.3 From 0970cb8010e590332b86de26a4746c7202c22363 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:09:38 +0200 Subject: minor update --- objective-c.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index ad2bedf9..7f87da6f 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -36,13 +36,13 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Primitive declarations - int myPrimitive1; - long myPrimitive2; + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; // Object declarations // Put the * in front of the variable names for strongly-typed object declarations - MyClass *myObject1; // Strong typing - id myObject2; // Weak typing + MyClass *myObject1 = nil; // Strong typing + id myObject2 = nil; // Weak typing // %@ is an object // 'description' is a convention to display the value of the Objects NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" -- cgit v1.2.3 From 24d9cde4883202d4b7c5db7dad8981b4a4000125 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:22:40 +0200 Subject: [NEW] Statements --- objective-c.html.markdown | 72 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 7f87da6f..ebae2fc7 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -99,6 +99,78 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Operators /////////////////////////////////////// + + // The operators works like in the C language + // For example: + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (Logical and) + 0 || 1; // => 1 (Logical or) + ~0x0F; // => 0xF0 (bitwise negation) + 0x0F & 0xF0; // => 0x00 (bitwise AND) + 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + + // If-Else statement + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Switch statement + switch (2) { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // While loops exist + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. + } // => prints "0, + 1, + 2, + 3," + + // For loops too + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", ii++); + } // => prints "0, + 1, + 2, + 3," + + // Foreach + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => prints "0, + 1, + 2, + 3," // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 5d800b25e427417c589f3cf2c3b19c18c178a11f Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:32:16 +0200 Subject: [NEW] Try-Catch-Finally --- objective-c.html.markdown | 49 +++++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 16 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index ebae2fc7..479d9ad5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -102,6 +102,8 @@ int main (int argc, const char * argv[]) // The operators works like in the C language // For example: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f 3 == 2; // => 0 (NO) 3 != 2; // => 1 (YES) 1 && 1; // => 1 (Logical and) @@ -127,7 +129,8 @@ int main (int argc, const char * argv[]) } // Switch statement - switch (2) { + switch (2) + { case 0: { NSLog(@"I am never run"); @@ -142,36 +145,50 @@ int main (int argc, const char * argv[]) } break; } - // While loops exist + // While loops statements int ii = 0; while (ii < 4) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. - } // => prints "0, - 1, - 2, - 3," + } // => prints "0," + "1," + "2," + "3," - // For loops too + // For loops statements int jj; for (jj=0; jj < 4; jj++) { NSLog(@"%d,", ii++); - } // => prints "0, - 1, - 2, - 3," + } // => prints "0," + "1," + "2," + "3," - // Foreach + // Foreach statements NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { NSLog(@"%@,", value); - } // => prints "0, - 1, - 2, - 3," + } // => prints "0," + "1," + "2," + "3," + // Try-Catch-Finally statements + @try + { + // Your statements here + @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => prints "Exception: File Not Found on System" + "Finally" + // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 50c3526247810078b6c63e2cbaf79bc226e873dc Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:34:12 +0200 Subject: minor updates --- objective-c.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 479d9ad5..6eac69a8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -151,9 +151,9 @@ int main (int argc, const char * argv[]) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. } // => prints "0," - "1," - "2," - "3," + // "1," + // "2," + // "3," // For loops statements int jj; @@ -161,9 +161,9 @@ int main (int argc, const char * argv[]) { NSLog(@"%d,", ii++); } // => prints "0," - "1," - "2," - "3," + // "1," + // "2," + // "3," // Foreach statements NSArray *values = @[@0, @1, @2, @3]; @@ -171,9 +171,9 @@ int main (int argc, const char * argv[]) { NSLog(@"%@,", value); } // => prints "0," - "1," - "2," - "3," + // "1," + // "2," + // "3," // Try-Catch-Finally statements @try @@ -187,7 +187,7 @@ int main (int argc, const char * argv[]) { NSLog(@"Finally"); } // => prints "Exception: File Not Found on System" - "Finally" + // "Finally" // Clean up the memory you used into your program [pool drain]; -- cgit v1.2.3 From 0d41a6405627b50f2839df3a3b019836f361ecc0 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:46:16 +0200 Subject: [UPDATE] Object Creation --- objective-c.html.markdown | 46 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 10 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 6eac69a8..f43081cf 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -201,27 +201,56 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Declare your class in a header(.h) file: - -@interface UserObject : NSObject +// Class Declaration Syntax: +// @interface : +// { +// Member variable declarations; +// } +// -/+ (type) Method declarations; +// @end +@interface MyClass : NSObject { - // instance variables + int count; + id data; + NSString *name; } +// Create the public getter/setter for the variable count +@property(assign) int count; + +// Methods ++/- (return type)methodSignature:(Parameter Type *)parameterName; -// Class method +// + for class method + (NSString *)classMethod; -// Instance method +// - for instance method - (NSString *)instanceMethodWithParmeter:(NSString *)string; - +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; +- @end // Implement the methods in an implementation (.m) file: @implementation UserObject +// Constructors are a way of creating classes +// This is a default constructor +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + + // Create an object instance by allocating memory and initializing it. + // An object is not fully functional until both steps have been completed. + UserObject *someObject = [[UserObject alloc] init]; + } + return self; +} + + (NSString *)classMethod { - return @"SomeString"; + return [[self alloc] init]; } - (NSString *)instanceMethodWithParmeter:(NSString *)string @@ -236,9 +265,6 @@ int main (int argc, const char * argv[]) @end -// Create an object instance by allocating memory and initializing it. An object is not fully functional until both steps have been completed. -UserObject *someObject = [[UserObject alloc] init]; - ##Calling Methods // The Objective-C model of object-oriented programming is based on message passing to object instances. -- cgit v1.2.3 From 3fe1c3c8a562427533439f385df952a00b36a998 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:49:23 +0200 Subject: minor update --- objective-c.html.markdown | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f43081cf..22791659 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -189,6 +189,18 @@ int main (int argc, const char * argv[]) } // => prints "Exception: File Not Found on System" // "Finally" + /////////////////////////////////////// + // Objects + /////////////////////////////////////// + + // Create an object instance by allocating memory and initializing it. + // An object is not fully functional until both steps have been completed. + MyClass *myObject = [[MyClass alloc] init]; + + // The Objective-C model of object-oriented programming is based on message passing to object instances. + // In Objective-C one does not simply call a method; one sends a message. + [myObject instanceMethodWithParmeter:@"Steve Jobs"]; + // Clean up the memory you used into your program [pool drain]; @@ -240,10 +252,6 @@ int main (int argc, const char * argv[]) if ((self = [super init])) { self.count = 1; - - // Create an object instance by allocating memory and initializing it. - // An object is not fully functional until both steps have been completed. - UserObject *someObject = [[UserObject alloc] init]; } return self; } @@ -265,18 +273,6 @@ int main (int argc, const char * argv[]) @end -##Calling Methods - -// The Objective-C model of object-oriented programming is based on message passing to object instances. -// In Objective-C one does not simply call a method; one sends a message. - -[someObject instanceMethodWithParmeter:@"Steve Jobs"]; - -##Nested Messages -// nested messages look like this: - -[someObject instanceMethodWithParmeter:[someObject otherMethodWithString:@"Jony Ive"]]; - ``` ## Further Reading -- cgit v1.2.3 From 664d592bc79c7dcc6c429bcee79965ef3df464f5 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:50:22 +0200 Subject: minor change --- objective-c.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 22791659..9d1178e1 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,6 +20,7 @@ Multi-line comments look like this. // Imports the Foundation headers with #import #import +#import "MyClass.h" // Your program's entry point is a function called // main with an integer return type. @@ -212,7 +213,7 @@ int main (int argc, const char * argv[]) // Classes And Functions /////////////////////////////////////// -// Declare your class in a header(.h) file: +// Declare your class in a header(MyClass.h) file: // Class Declaration Syntax: // @interface : // { @@ -241,7 +242,7 @@ int main (int argc, const char * argv[]) - @end -// Implement the methods in an implementation (.m) file: +// Implement the methods in an implementation (MyClass.m) file: @implementation UserObject -- cgit v1.2.3 From 0932765947b14407aa41fbe7ded00ca37a25f5c6 Mon Sep 17 00:00:00 2001 From: Yannick Loriot Date: Tue, 13 Aug 2013 16:58:13 +0200 Subject: [NEW] Protocol Implementation --- objective-c.html.markdown | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 9d1178e1..187ea30a 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -215,20 +215,22 @@ int main (int argc, const char * argv[]) // Declare your class in a header(MyClass.h) file: // Class Declaration Syntax: -// @interface : +// @interface ClassName : ParentClassName // { // Member variable declarations; // } // -/+ (type) Method declarations; // @end -@interface MyClass : NSObject +@interface MyClass : NSObject { int count; id data; NSString *name; } -// Create the public getter/setter for the variable count -@property(assign) int count; +// Convenience notation to auto generate public getter and setter +@property int count; +@property (copy) NSString *name; // Copy the object during assignment. +@property (readonly) id data; // Declare only a getter method. // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -246,8 +248,13 @@ int main (int argc, const char * argv[]) @implementation UserObject +// Call when the object is releasing +- (void)dealloc +{ +} + // Constructors are a way of creating classes -// This is a default constructor +// This is a default constructor which is call when the object is creating - (id)init { if ((self = [super init])) @@ -272,8 +279,25 @@ int main (int argc, const char * argv[]) return @42; } +// Methods declared into MyProtocol +- (void)myProtocolMethod +{ + // statements +} + @end +/* + * A protocol declares methods that can be implemented by any class. + * Protocols are not classes themselves. They simply define an interface + * that other objects are responsible for implementing. + * / +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + + ``` ## Further Reading -- cgit v1.2.3 From 50e49eced17ee758d47ca06141ee2b0e27ea2ee8 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 13 Aug 2013 10:30:44 -0700 Subject: Line length edits to objective c --- objective-c.html.markdown | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 187ea30a..2b1b3c67 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -11,7 +11,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```Objective-C +```cpp // Single-line comments start with // /* @@ -180,7 +180,8 @@ int main (int argc, const char * argv[]) @try { // Your statements here - @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"File Not Found on System" userInfo:nil]; } @catch (NSException * e) { NSLog(@"Exception: %@", e); @@ -198,9 +199,10 @@ int main (int argc, const char * argv[]) // An object is not fully functional until both steps have been completed. MyClass *myObject = [[MyClass alloc] init]; - // The Objective-C model of object-oriented programming is based on message passing to object instances. + // The Objective-C model of object-oriented programming is based on message + // passing to object instances. // In Objective-C one does not simply call a method; one sends a message. - [myObject instanceMethodWithParmeter:@"Steve Jobs"]; + [myObject instanceMethodWithParameter:@"Steve Jobs"]; // Clean up the memory you used into your program [pool drain]; @@ -241,7 +243,7 @@ int main (int argc, const char * argv[]) // - for instance method - (NSString *)instanceMethodWithParmeter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -- + @end // Implement the methods in an implementation (MyClass.m) file: @@ -291,7 +293,7 @@ int main (int argc, const char * argv[]) * A protocol declares methods that can be implemented by any class. * Protocols are not classes themselves. They simply define an interface * that other objects are responsible for implementing. - * / + */ @protocol MyProtocol - (void)myProtocolMethod; @end -- cgit v1.2.3 From 50ac50f05f82c3b3069329634f373c1ba55263c0 Mon Sep 17 00:00:00 2001 From: Seva Baskin Date: Thu, 15 Aug 2013 23:25:51 +0100 Subject: Update objective-c.html.markdown Fixed a few typos --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 2b1b3c67..b92e3218 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -160,7 +160,7 @@ int main (int argc, const char * argv[]) int jj; for (jj=0; jj < 4; jj++) { - NSLog(@"%d,", ii++); + NSLog(@"%d,", jj++); } // => prints "0," // "1," // "2," @@ -256,7 +256,7 @@ int main (int argc, const char * argv[]) } // Constructors are a way of creating classes -// This is a default constructor which is call when the object is creating +// This is a default constructor which is called when the object is creating - (id)init { if ((self = [super init])) -- cgit v1.2.3 From dcdfd9114f3d606ede2a3d4967e7699579427e46 Mon Sep 17 00:00:00 2001 From: JakeHurlbut Date: Sat, 17 Aug 2013 18:06:23 -0400 Subject: Corrected Array Object NSLog Call --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index b92e3218..9e9f43e7 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -90,7 +90,7 @@ int main (int argc, const char * argv[]) // Array object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdObject); // Print "Third number = 3" + NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; -- cgit v1.2.3 From 01150e5309c2c924df02405c66d9b5cfb759eac9 Mon Sep 17 00:00:00 2001 From: Dave Caunt Date: Wed, 4 Sep 2013 12:38:47 +0100 Subject: Fixed For loop example so that jj is not incremented twice in each iteration of the loop --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 9e9f43e7..e8c979d8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -160,7 +160,7 @@ int main (int argc, const char * argv[]) int jj; for (jj=0; jj < 4; jj++) { - NSLog(@"%d,", jj++); + NSLog(@"%d,", jj); } // => prints "0," // "1," // "2," -- cgit v1.2.3 From 147cc58761c8199a56605b71db741422330f940f Mon Sep 17 00:00:00 2001 From: Dave Caunt Date: Wed, 4 Sep 2013 12:56:58 +0100 Subject: Fixed typo in Parameter --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index e8c979d8..98204a9a 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -241,7 +241,7 @@ int main (int argc, const char * argv[]) + (NSString *)classMethod; // - for instance method -- (NSString *)instanceMethodWithParmeter:(NSString *)string; +- (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; @end @@ -271,7 +271,7 @@ int main (int argc, const char * argv[]) return [[self alloc] init]; } -- (NSString *)instanceMethodWithParmeter:(NSString *)string +- (NSString *)instanceMethodWithParameter:(NSString *)string { return @"New string"; } -- cgit v1.2.3 From 1e6aff4a7b43b8f528951b0c9cb753ae62c9c649 Mon Sep 17 00:00:00 2001 From: Dave Caunt Date: Wed, 4 Sep 2013 12:58:06 +0100 Subject: Fixed inconsistencies in class implementation and protocol naming --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 98204a9a..926a4a0d 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -223,7 +223,7 @@ int main (int argc, const char * argv[]) // } // -/+ (type) Method declarations; // @end -@interface MyClass : NSObject +@interface MyClass : NSObject { int count; id data; @@ -248,7 +248,7 @@ int main (int argc, const char * argv[]) // Implement the methods in an implementation (MyClass.m) file: -@implementation UserObject +@implementation MyClass // Call when the object is releasing - (void)dealloc -- cgit v1.2.3 From 3ea52a10845e8e6a052443c12abdc012534c6210 Mon Sep 17 00:00:00 2001 From: Wesley Hill Date: Mon, 9 Sep 2013 01:30:43 +0100 Subject: corrected issue on floating point literals. --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 926a4a0d..1ed0ed58 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -80,7 +80,7 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piFloat); NSNumber *piDoubleNumber = @3.1415926535; - piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; NSLog(@"%f", piDouble); // BOOL literals -- cgit v1.2.3 From 5d5f3309faf8c6cf0bb5242ea7220e4ae772d6a3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 21 Dec 2013 17:37:19 -0600 Subject: Add more description to @property getters and setters. --- objective-c.html.markdown | 3 +++ 1 file changed, 3 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 1ed0ed58..0a197e03 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -233,6 +233,9 @@ int main (int argc, const char * argv[]) @property int count; @property (copy) NSString *name; // Copy the object during assignment. @property (readonly) id data; // Declare only a getter method. +// To access variable in implementation file, use '_' followed by variable name: +_count = 5; +NSLog("%@", _count); // => prints 5 to console // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -- cgit v1.2.3 From 643a3ec67bb5d7b453b4a4d59bbb8b254eccb0db Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sat, 21 Dec 2013 17:37:19 -0600 Subject: Add getters and setters examples. --- objective-c.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0a197e03..1cfe8ed6 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -233,9 +233,13 @@ int main (int argc, const char * argv[]) @property int count; @property (copy) NSString *name; // Copy the object during assignment. @property (readonly) id data; // Declare only a getter method. -// To access variable in implementation file, use '_' followed by variable name: +// To access public variable in implementation file, use '_' followed by variable name: _count = 5; -NSLog("%@", _count); // => prints 5 to console +NSLog(@"%d", _count); // prints => 5 +// To access public variable outside implementation file, @property generates setter method +// automatically. Method name is 'set' followed by @property variable name: +[objInitVar setCount:10]; // objInitVar = variable of object instance @property resides in. +NSLog(@"%@", [objInitVar count]); // prints => 10 // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -- cgit v1.2.3 From 0b73244aa3c53d51a7031a04a6cb7f85895af101 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 22 Dec 2013 10:37:02 -0600 Subject: Add data types with examples. --- objective-c.html.markdown | 58 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 9 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 1cfe8ed6..0131a34c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -50,53 +50,93 @@ int main (int argc, const char * argv[]) // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // Print "Hello World!" + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + // The mutable version of NSString is NSMutableString that allows to edit + // individual characters or append strings together. + NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; + [mutableString appendString:@" World!"]; + NSLog(@"%@", mutableString); // prints => "Hello World!" // Character literals NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; + char theLetterZ = [theLetterZNumber charValue]; // or 'Z' NSLog(@"%c", theLetterZ); // Integral literals NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; + int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 + NSLog(@"%hu", fortyTwoUnsigned); NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); + NSNumber *fortyTwoLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 + NSLog(@"%lu", fiftyThreeUnsigned); + // Floating point literals NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; - NSLog(@"%f", piFloat); + float piFloat = [piFloatNumber floatValue]; // or 3.141592654f + NSLog(@"%f", piFloat); // prints => 3.141592654 + NSLog(@"%5.2f", piFloat); // prints => " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // prints => "3.14" + + // NSDecimalNumber is Objective-C's fixed-point class more precise then float or double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimal isn't able to use standard +, -, *, / operators. NSDecimalNumber has its own: + [oneDecNum decimalNumberByAdding:twoDecNum]; // add + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable. // BOOL literals NSNumber *yesNumber = @YES; NSNumber *noNumber = @NO; + // or + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // prints => 1 // Array object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + // NSMutableArray is mutable version of NSArray allowing to change items in array + // and extend or shrink array object. Convenient, but not as efficient as NSArray. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Hello"]; + [mutableArray addObject:@"World"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // prints => "World" // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + // Set object + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // prints => {(Hello, World)} + /////////////////////////////////////// // Operators /////////////////////////////////////// -- cgit v1.2.3 From 18f669089e0f5a65adfdfeddaa571a801dd4b865 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 23 Dec 2013 02:26:11 -0600 Subject: Add examples of methods to work with NSSets. Add note of NSSets being unordered. Remove for loop to iterate on NSSet. Moved for loop to loop section. --- objective-c.html.markdown | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0131a34c..95012152 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -50,9 +50,8 @@ int main (int argc, const char * argv[]) // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // prints => "Hello World!" - // The mutable version of NSString is NSMutableString that allows to edit - // individual characters or append strings together. + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + // NSMutableString is a mutable version of the NSString object. NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" @@ -98,11 +97,11 @@ int main (int argc, const char * argv[]) NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // prints => "3.14" - // NSDecimalNumber is Objective-C's fixed-point class more precise then float or double + // NSDecimalNumber is a fixed-point class that's more precise then float or double NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; - // NSDecimal isn't able to use standard +, -, *, / operators. NSDecimalNumber has its own: - [oneDecNum decimalNumberByAdding:twoDecNum]; // add + // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: + [oneDecNum decimalNumberByAdding:twoDecNum]; [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; @@ -132,10 +131,12 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + // NSMutableDictionary also available as mutable dictionary object. // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; - NSLog(@"%@", set); // prints => {(Hello, World)} + NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) + // NSMutableSet also available as mutable set object. /////////////////////////////////////// // Operators @@ -216,6 +217,14 @@ int main (int argc, const char * argv[]) // "2," // "3," + // Object for loop statement. Can be used with any Objective-C object type. + for (id item in values) { + NSLog(@"%@,", item); + } // => prints "0," + // "1," + // "2," + // "3," + // Try-Catch-Finally statements @try { @@ -278,7 +287,7 @@ _count = 5; NSLog(@"%d", _count); // prints => 5 // To access public variable outside implementation file, @property generates setter method // automatically. Method name is 'set' followed by @property variable name: -[objInitVar setCount:10]; // objInitVar = variable of object instance @property resides in. +[objInitVar setCount:10]; // objInitVar = random object instance @property resides in. NSLog(@"%@", [objInitVar count]); // prints => 10 // Methods -- cgit v1.2.3 From f15a2b5f782b0f5fb2de6359353f948218860484 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 26 Dec 2013 12:20:16 -0600 Subject: Add more data type examples. Add NSMutableSet examples. --- objective-c.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 95012152..bbdbac4c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -131,12 +131,19 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" - // NSMutableDictionary also available as mutable dictionary object. + // NSMutableDictionary also available as a mutable dictionary object. + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"value1" forKey:@"key1"]; + [mutableDictionary setObject:@"value2" forKey:@"key2"]; + [mutableDictionary removeObjectForKey:@"key1"]; // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) - // NSMutableSet also available as mutable set object. + // NSMutableSet also available as a mutable set object. + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Hello"]; + [mutableSet addObject:@"Hello"]; /////////////////////////////////////// // Operators -- cgit v1.2.3 From 03ada8d9751993ad1b36d3d5848678b31ac9021c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 26 Dec 2013 22:26:34 -0600 Subject: Add instance variable definition examples. --- objective-c.html.markdown | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index bbdbac4c..419c0475 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -74,7 +74,7 @@ int main (int argc, const char * argv[]) short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 NSLog(@"%hu", fortyTwoUnsigned); @@ -82,7 +82,7 @@ int main (int argc, const char * argv[]) long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); - NSNumber *fortyTwoLongNumber = @53L; + NSNumber *fortyTwoLongNumber = @53L; unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 NSLog(@"%lu", fiftyThreeUnsigned); @@ -93,7 +93,7 @@ int main (int argc, const char * argv[]) NSLog(@"%5.2f", piFloat); // prints => " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 + double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); NSLog(@"%4.2f", piDouble); // prints => "3.14" @@ -112,7 +112,7 @@ int main (int argc, const char * argv[]) NSNumber *noNumber = @NO; // or BOOL yesBool = YES; - BOOL noBool = NO; + BOOL noBool = NO; NSLog(@"%i", yesBool); // prints => 1 // Array object @@ -144,6 +144,7 @@ int main (int argc, const char * argv[]) NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; [mutableSet addObject:@"Hello"]; + NSLog(@"%@", mutableSet); // prints => {(Hello)} /////////////////////////////////////// // Operators @@ -281,11 +282,12 @@ int main (int argc, const char * argv[]) // @end @interface MyClass : NSObject { - int count; - id data; - NSString *name; + // Instance variable declarations (can exist in either interface or implementation file) + int count; // Protected access by default. + @private id data; // Private access. (More convenient to declare in implementation file) + NSString *name; } -// Convenience notation to auto generate public getter and setter +// Convenient notation to auto generate public access getter and setter @property int count; @property (copy) NSString *name; // Copy the object during assignment. @property (readonly) id data; // Declare only a getter method. @@ -294,8 +296,16 @@ _count = 5; NSLog(@"%d", _count); // prints => 5 // To access public variable outside implementation file, @property generates setter method // automatically. Method name is 'set' followed by @property variable name: -[objInitVar setCount:10]; // objInitVar = random object instance @property resides in. -NSLog(@"%@", [objInitVar count]); // prints => 10 +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +[myClass setCount:10]; +NSLog(@"%@", [myClass count]); // prints => 10 +// You can customize the getter and setter names instead of using default 'set' name: +@property (getter=countGet, setter=countSet:) int count; +[myClass countSet:32]; +NSLog(@"%i", [myClass countGet]); // prints => 32 +// For convenience, you may use dot notation to set object instance variables: +myClass.count = 45; +NSLog(@"%i", myClass.count); // prints => 45 // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -310,8 +320,9 @@ NSLog(@"%@", [objInitVar count]); // prints => 10 @end // Implement the methods in an implementation (MyClass.m) file: - -@implementation MyClass +@implementation MyClass { + long count; // Private access instance variable. +} // Call when the object is releasing - (void)dealloc -- cgit v1.2.3 From ce770c61df6670f3ac20241dae6314dea5a9c846 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 23 Dec 2013 02:19:18 -0600 Subject: Add simple NSSet example. --- objective-c.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 419c0475..98019404 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -146,6 +146,10 @@ int main (int argc, const char * argv[]) [mutableSet addObject:@"Hello"]; NSLog(@"%@", mutableSet); // prints => {(Hello)} + // Set object + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // prints => {(Hello, World)} + /////////////////////////////////////// // Operators /////////////////////////////////////// -- cgit v1.2.3 From dff26a28afbdc138cd21154e733839f52afaaab9 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 31 Dec 2013 13:50:37 -0600 Subject: Add memory management examples. --- objective-c.html.markdown | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 98019404..9a11ebc8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -377,6 +377,34 @@ NSLog(@"%i", myClass.count); // prints => 45 @end +/////////////////////////////////////// +// Memory Management +/////////////////////////////////////// +/* +For each object used in an application, memory must be allocated for that object. When the application +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as +there is at least one reference to an object (also called "owning" an object), then the object +will be available to use (known as "ownership"). + +When an instance owns an object, its reference counter is increments by one. When the +object is released, the reference counter decrements by one. When reference count is zero, +the object is removed from memory. + +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. +*/ + +MyClass *classVar = [MyClass alloc]; // alloc sets classVar's reference count to one. Returns pointer to object. +[classVar release]; // Decrements classVar's reference count. +// retain claims ownership of existing object instance and increments reference count. Returns pointer to object. +MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. +[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. + +// @property can use retain or assign as well for small convenient definitions. +@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). +@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). + ``` ## Further Reading -- cgit v1.2.3 From 8e04611520cc385ccfd96ca1e8cfd8e30fc2ce40 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 31 Dec 2013 14:04:07 -0600 Subject: Add automatic reference counting examples. --- objective-c.html.markdown | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 9a11ebc8..406b2e92 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -405,6 +405,21 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still @property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). @property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// you must not use retain, relase, or autorelease. +MyClass *arcMyClass = [[MyClass alloc] init]; // Without ARC, you will need to call: [arcMyClass release] after +// you're done using arcMyClass. But with ARC, there is no need. It will insert this release statement for you. + +// As for the "assign" and "retain" @property attributes, with ARC you use "weak" and "strong". +@property (weak) MyClass *weakVar; // weak does not take ownership of object. If original instance's reference count +// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. +@property (strong) MyClass *strongVar; // strong takes ownership of object. Ensures object will stay in memory to use. + +// For regular variables (not @property declared variables), use the following: +__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. +__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. +__unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set to nil when existing object is released. ``` ## Further Reading -- cgit v1.2.3 From fff847f09e67144a67ec6e0db2198273ef8d91ad Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 1 Jan 2014 19:01:50 -0600 Subject: Add @autoreleasepool as alternative to NSAutoreleasePool object. --- objective-c.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 406b2e92..b9460127 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -28,7 +28,9 @@ int main (int argc, const char * argv[]) { // Create an autorelease pool to manage the memory into the program NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - + // If using automatic reference counting (ARC), use @autoreleasepool instead: + @autoreleasepool { + // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" @@ -267,6 +269,9 @@ int main (int argc, const char * argv[]) // Clean up the memory you used into your program [pool drain]; + + // End of @autoreleasepool. + } // End the program return 0; -- cgit v1.2.3 From db691596bb0a549a01c22e097d0c8d2d84beed5f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 3 Jan 2014 12:50:35 -0600 Subject: Move statements out of @interface that did not allow file to compile. Fix various typos/confusing wording. --- objective-c.html.markdown | 68 +++++++++++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 29 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index b9460127..4ba1e5d5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -281,41 +281,30 @@ int main (int argc, const char * argv[]) // Classes And Functions /////////////////////////////////////// -// Declare your class in a header(MyClass.h) file: -// Class Declaration Syntax: +// Declare your class in a header file (MyClass.h): +// Class declaration syntax: // @interface ClassName : ParentClassName // { -// Member variable declarations; +// type name; <= variable declarations; // } -// -/+ (type) Method declarations; +// @property type name; <= property declarations. +// -/+ (type) Method declarations; <= Method declarations. // @end -@interface MyClass : NSObject +@interface MyClass : NSObject // NSObject is Objective-C base object class. { - // Instance variable declarations (can exist in either interface or implementation file) + // Instance variable declarations (can exist in either interface or implementation file). int count; // Protected access by default. - @private id data; // Private access. (More convenient to declare in implementation file) + @private id data; // Private access. (More convenient to declare in implementation file). NSString *name; } -// Convenient notation to auto generate public access getter and setter -@property int count; -@property (copy) NSString *name; // Copy the object during assignment. -@property (readonly) id data; // Declare only a getter method. -// To access public variable in implementation file, use '_' followed by variable name: -_count = 5; -NSLog(@"%d", _count); // prints => 5 -// To access public variable outside implementation file, @property generates setter method -// automatically. Method name is 'set' followed by @property variable name: -MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. -[myClass setCount:10]; -NSLog(@"%@", [myClass count]); // prints => 10 +// Convenient notation for public access variables to auto generate a setter method. +// By default, setter method name is 'set' followed by @property variable name. +@property int count; // Setter name = 'setCount' +@property (copy) NSString *name; // (copy) => Copy the object during assignment. +@property (readonly) id data; // (readonly) => Declare only a getter method. // You can customize the getter and setter names instead of using default 'set' name: -@property (getter=countGet, setter=countSet:) int count; -[myClass countSet:32]; -NSLog(@"%i", [myClass countGet]); // prints => 32 -// For convenience, you may use dot notation to set object instance variables: -myClass.count = 45; -NSLog(@"%i", myClass.count); // prints => 45 - +@property (getter=lengthGet, setter=lengthSet:) int length; + // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -326,13 +315,34 @@ NSLog(@"%i", myClass.count); // prints => 45 - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -@end +@end // States the end of the interface. + + +// To access public variables from the implementation file, @property generates a setter method +// automatically. Method name is 'set' followed by @property variable name: +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +[myClass setCount:10]; +NSLog(@"%@", [myClass count]); // prints => 10 +// Or using the custom getter and setter method defined in @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // prints => 32 +// For convenience, you may use dot notation to set and access object instance variables: +myClass.count = 45; +NSLog(@"%i", myClass.count); // prints => 45 + // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { - long count; // Private access instance variable. + long distance; // Private access instance variable. } +// To access public variable from the interface file, use '_' followed by variable name: +_count = 5; // References "int count" from MyClass interface. +NSLog(@"%d", _count); // prints => 5 +// Access variables defined in implementation file: +distance = 18; // References "long distance" from MyClass implementation. +NSLog(@"%li", distance); // prints => 18 + // Call when the object is releasing - (void)dealloc { @@ -370,7 +380,7 @@ NSLog(@"%i", myClass.count); // prints => 45 // statements } -@end +@end // States the end of the implementation. /* * A protocol declares methods that can be implemented by any class. -- cgit v1.2.3 From 527fc37efa9cdd9881a2afa3b5e217b91a12db9e Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 3 Jan 2014 12:52:23 -0600 Subject: Remove broken Apple website link to Learning Objective-C and replaced with Programming with Objective-C Apple book link. --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 4ba1e5d5..248e132e 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -441,6 +441,6 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) -[Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) +[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From d935f8fd4e09a2e72a679d75b732d18e451eaf8a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 19:16:47 -0600 Subject: Edit code for all snippets to compile properly. Re-word some descriptions. --- objective-c.html.markdown | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 248e132e..53f155a6 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -76,16 +76,16 @@ int main (int argc, const char * argv[]) short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:41]; - unsigned short fortyTwoUnsigned = [fortyTwoShortNumber unsignedShortValue]; // or 41 - NSLog(@"%hu", fortyTwoUnsigned); + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41 + NSLog(@"%u", fortyOneUnsigned); NSNumber *fortyTwoLongNumber = @42L; long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); - NSNumber *fortyTwoLongNumber = @53L; - unsigned long fiftyThreeUnsigned = [fortyTwoLongNumber unsignedLongValue]; // or 53 + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // or 53 NSLog(@"%lu", fiftyThreeUnsigned); // Floating point literals @@ -118,6 +118,7 @@ int main (int argc, const char * argv[]) NSLog(@"%i", yesBool); // prints => 1 // Array object + // May contain different data types, but must be an Objective-C object. NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" @@ -148,10 +149,6 @@ int main (int argc, const char * argv[]) [mutableSet addObject:@"Hello"]; NSLog(@"%@", mutableSet); // prints => {(Hello)} - // Set object - NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; - NSLog(@"%@", set); // prints => {(Hello, World)} - /////////////////////////////////////// // Operators /////////////////////////////////////// @@ -299,9 +296,9 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int count; // Setter name = 'setCount' +@property int count; // Setter method name = 'setCount' @property (copy) NSString *name; // (copy) => Copy the object during assignment. -@property (readonly) id data; // (readonly) => Declare only a getter method. +@property (readonly) id data; // (readonly) => Cannot set value outside interface. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -322,7 +319,7 @@ int main (int argc, const char * argv[]) // automatically. Method name is 'set' followed by @property variable name: MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. [myClass setCount:10]; -NSLog(@"%@", [myClass count]); // prints => 10 +NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: [myClass lengthSet:32]; NSLog(@"%i", [myClass lengthGet]); // prints => 32 @@ -349,7 +346,7 @@ NSLog(@"%li", distance); // prints => 18 } // Constructors are a way of creating classes -// This is a default constructor which is called when the object is creating +// This is a default constructor which is called when the object is initialized. - (id)init { if ((self = [super init])) @@ -410,31 +407,34 @@ With all object interactions, follow the pattern of: (1) create the object, (2) use the object, (3) then free the object from memory. */ -MyClass *classVar = [MyClass alloc]; // alloc sets classVar's reference count to one. Returns pointer to object. +MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object. [classVar release]; // Decrements classVar's reference count. -// retain claims ownership of existing object instance and increments reference count. Returns pointer to object. +// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object. MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. [classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. -// @property can use retain or assign as well for small convenient definitions. +// @property can use 'retain' and 'assign' as well for small convenient definitions. @property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). @property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). // ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, // you must not use retain, relase, or autorelease. -MyClass *arcMyClass = [[MyClass alloc] init]; // Without ARC, you will need to call: [arcMyClass release] after -// you're done using arcMyClass. But with ARC, there is no need. It will insert this release statement for you. +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... code using arcMyClass +// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, +// there is no need. It will insert this release statement for you. -// As for the "assign" and "retain" @property attributes, with ARC you use "weak" and "strong". -@property (weak) MyClass *weakVar; // weak does not take ownership of object. If original instance's reference count +// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'. +@property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count // is set to zero, weakVar will automatically receive value of nil to avoid application crashing. -@property (strong) MyClass *strongVar; // strong takes ownership of object. Ensures object will stay in memory to use. +@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use. // For regular variables (not @property declared variables), use the following: __strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. __weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. -__unsafe_unretained NSArray *unsafeArray; // Like __weak but unsafeArray not set to nil when existing object is released. +__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. ``` ## Further Reading -- cgit v1.2.3 From dcf6331eec9faeefc91eb53f90f17408b7d01857 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 20:21:29 -0600 Subject: Add name and github page to contributors list. --- objective-c.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 53f155a6..98179f97 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -4,6 +4,7 @@ language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] filename: LearnObjectiveC.m --- -- cgit v1.2.3 From bfa623ac4997cadf132676c49cb92975173ce741 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 20:28:42 -0600 Subject: Removed NSLog() statements inside @implementation where not allowed. --- objective-c.html.markdown | 2 -- 1 file changed, 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 98179f97..886f80e2 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -336,10 +336,8 @@ NSLog(@"%i", myClass.count); // prints => 45 // To access public variable from the interface file, use '_' followed by variable name: _count = 5; // References "int count" from MyClass interface. -NSLog(@"%d", _count); // prints => 5 // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. -NSLog(@"%li", distance); // prints => 18 // Call when the object is releasing - (void)dealloc -- cgit v1.2.3 From afa93d54ad7d370b9b05434c2cf4a09c5b695ddf Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Tue, 7 Jan 2014 08:41:07 -0600 Subject: Fix typos. --- objective-c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 886f80e2..a70351b5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -288,7 +288,7 @@ int main (int argc, const char * argv[]) // @property type name; <= property declarations. // -/+ (type) Method declarations; <= Method declarations. // @end -@interface MyClass : NSObject // NSObject is Objective-C base object class. +@interface MyClass : NSObject // NSObject is Objective-C's base object class. { // Instance variable declarations (can exist in either interface or implementation file). int count; // Protected access by default. @@ -334,7 +334,7 @@ NSLog(@"%i", myClass.count); // prints => 45 long distance; // Private access instance variable. } -// To access public variable from the interface file, use '_' followed by variable name: +// To access a public variable from the interface file, use '_' followed by variable name: _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. -- cgit v1.2.3 From 5ad738af38b4642257f5036ac5ed7dbc27f4e187 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 1 Jan 2014 17:20:23 -0600 Subject: Add example of calling instance and class methods. --- objective-c.html.markdown | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index a70351b5..e1834bf8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -306,10 +306,11 @@ int main (int argc, const char * argv[]) // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -// + for class method +// + for class method. + (NSString *)classMethod; ++ (MyClass *)myClassFromName:(NSString *)name; -// - for instance method +// - for instance methods. - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; @@ -329,6 +330,14 @@ myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Call class methods: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Call instance methods: +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. -- cgit v1.2.3 From 7496526cf447c6f5459a9b32448d2ba6e0f60dc0 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 20:18:45 -0600 Subject: Add more examples of methods available to objects. --- objective-c.html.markdown | 49 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 8 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index e1834bf8..cdf89338 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -297,9 +297,10 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int count; // Setter method name = 'setCount' -@property (copy) NSString *name; // (copy) => Copy the object during assignment. -@property (readonly) id data; // (readonly) => Cannot set value outside interface. +@property int propInt; // Setter method name = 'setCount' +@property (copy) id copyId; // (copy) => Copy the object during assignment. +// (readonly) => Cannot set value outside interface. +@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -308,12 +309,15 @@ int main (int argc, const char * argv[]) // + for class method. + (NSString *)classMethod; -+ (MyClass *)myClassFromName:(NSString *)name; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; // - for instance methods. - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; +// Constructor methods with arguments: +- (id)initWithDistance:(int)defaultDistance; + @end // States the end of the interface. @@ -341,6 +345,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. + NSNumber height; } // To access a public variable from the interface file, use '_' followed by variable name: @@ -348,27 +353,49 @@ _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. -// Call when the object is releasing +// Called before calling any class methods or instantiating any objects. ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} + +// Counterpart to initialize method. Called when an object's reference count is zero. - (void)dealloc { + [height release]; // If not using ARC, make sure to release class variable objects + [super dealloc]; // and call parent class dealloc. } -// Constructors are a way of creating classes +// Constructors are a way of creating instances of classes. // This is a default constructor which is called when the object is initialized. - (id)init { - if ((self = [super init])) + if ((self = [super init])) // 'super' used to access methods from parent class. { - self.count = 1; + self.count = 1; // 'self' used for object to send messages to itself. } return self; } +// Can create constructors that contain arguments: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + (NSString *)classMethod { return [[self alloc] init]; } ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + - (NSString *)instanceMethodWithParameter:(NSString *)string { return @"New string"; @@ -379,6 +406,12 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } +// If you create a method in @implementation but do not include in @interface, it is private. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Calls private method. + // Methods declared into MyProtocol - (void)myProtocolMethod { -- cgit v1.2.3 From a16841e0497d033af29257233b2c3e8e93b7987f Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 6 Jan 2014 22:18:54 -0600 Subject: Add selector and @synthesize examples. --- objective-c.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index cdf89338..38b2cc52 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -333,6 +333,20 @@ NSLog(@"%i", [myClass lengthGet]); // prints => 32 myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Selectors. +// Way of dynamically represent methods. Used to call methods of a class, pass methods +// through functions to tell other classes they should call it, and save to methods +// as a variable. +// SEL is data type. @selector() returns a selector from method name provided. +// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. + // Must put method arguments into one object to send to performSelector. + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method +} else { + NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); +} // Call class methods: NSString *classMethodString = [MyClass classMethod]; @@ -352,6 +366,8 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell _count = 5; // References "int count" from MyClass interface. // Access variables defined in implementation file: distance = 18; // References "long distance" from MyClass implementation. +// To use @property variable in implementation, use @synthesize to create accessor variable: +@synthesize roString = _roString; // _roString available now in @implementation. // Called before calling any class methods or instantiating any objects. + (void)initialize -- cgit v1.2.3 From eab35e826eb86744d98a3fc424ebca6ccf432390 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 13:03:31 -0600 Subject: Organize branch changes. --- objective-c.html.markdown | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 38b2cc52..f2787649 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -297,9 +297,9 @@ int main (int argc, const char * argv[]) } // Convenient notation for public access variables to auto generate a setter method. // By default, setter method name is 'set' followed by @property variable name. -@property int propInt; // Setter method name = 'setCount' +@property int propInt; // Setter method name = 'setPropInt' @property (copy) id copyId; // (copy) => Copy the object during assignment. -// (readonly) => Cannot set value outside interface. +// (readonly) => Cannot set value outside @interface. @property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -307,16 +307,17 @@ int main (int argc, const char * argv[]) // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; -// + for class method. +// + for class methods: + (NSString *)classMethod; + (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; -// - for instance methods. +// - for instance methods: - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; // Constructor methods with arguments: - (id)initWithDistance:(int)defaultDistance; +// Objective-C method names are very descriptive. Always name methods according to their arguments. @end // States the end of the interface. @@ -333,29 +334,30 @@ NSLog(@"%i", [myClass lengthGet]); // prints => 32 myClass.count = 45; NSLog(@"%i", myClass.count); // prints => 45 +// Call class methods: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Call instance methods: +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + // Selectors. -// Way of dynamically represent methods. Used to call methods of a class, pass methods -// through functions to tell other classes they should call it, and save to methods +// Way to dynamically represent methods. Used to call methods of a class, pass methods +// through functions to tell other classes they should call it, and to save methods // as a variable. -// SEL is data type. @selector() returns a selector from method name provided. +// SEL is the data type. @selector() returns a selector from method name provided. // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. - // Must put method arguments into one object to send to performSelector. + // Must put all method arguments into one object to send to performSelector function. NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; - [myClass performSelector:selectorVar withObject:arguments]; // Calls the method + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method. } else { + // NSStringFromSelector() returns a NSString of the method name of a given selector. NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); } -// Call class methods: -NSString *classMethodString = [MyClass classMethod]; -MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; - -// Call instance methods: -MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. -NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; - // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { long distance; // Private access instance variable. @@ -384,13 +386,13 @@ distance = 18; // References "long distance" from MyClass implementation. [super dealloc]; // and call parent class dealloc. } -// Constructors are a way of creating instances of classes. +// Constructors are a way of creating instances of a class. // This is a default constructor which is called when the object is initialized. - (id)init { if ((self = [super init])) // 'super' used to access methods from parent class. { - self.count = 1; // 'self' used for object to send messages to itself. + self.count = 1; // 'self' used for object to call itself. } return self; } @@ -422,7 +424,7 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } -// If you create a method in @implementation but do not include in @interface, it is private. +// To create a private method, create the method in the @implementation but not in the @interface. - (NSNumber *)secretPrivateMethod { return @72; } -- cgit v1.2.3 From 01e3455d90e7e542d0b38c9e46865a06ea018237 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sat, 11 Jan 2014 19:27:47 +0100 Subject: [UPDATE] Import Details --- objective-c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f2787649..3390c69b 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```cpp +```objective-c // Single-line comments start with // /* @@ -20,9 +20,15 @@ Multi-line comments look like this. */ // Imports the Foundation headers with #import +// Use <> to import global files (in general frameworks) +// Use "" to import local files (from project) #import #import "MyClass.h" +// If you enable modules for iOS >= 7.0 or OS X >= 10.9 projects in +// Xcode 5 you can import frameworks like that: +@import Foundation; + // Your program's entry point is a function called // main with an integer return type. int main (int argc, const char * argv[]) -- cgit v1.2.3 From d5c4e851da8e5cf58279941af81531e3fd8b1035 Mon Sep 17 00:00:00 2001 From: Yannick Date: Sat, 11 Jan 2014 19:51:41 +0100 Subject: [REMOVE] dots at the end of the comments --- objective-c.html.markdown | 130 +++++++++++++++++++++++----------------------- 1 file changed, 65 insertions(+), 65 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 3390c69b..453a42a5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -16,7 +16,7 @@ It is a general-purpose, object-oriented programming language that adds Smalltal // Single-line comments start with // /* -Multi-line comments look like this. +Multi-line comments look like this */ // Imports the Foundation headers with #import @@ -30,7 +30,7 @@ Multi-line comments look like this. @import Foundation; // Your program's entry point is a function called -// main with an integer return type. +// main with an integer return type int main (int argc, const char * argv[]) { // Create an autorelease pool to manage the memory into the program @@ -60,7 +60,7 @@ int main (int argc, const char * argv[]) // String NSString *worldString = @"World"; NSLog(@"Hello %@!", worldString); // prints => "Hello World!" - // NSMutableString is a mutable version of the NSString object. + // NSMutableString is a mutable version of the NSString object NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" @@ -114,7 +114,7 @@ int main (int argc, const char * argv[]) [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; - NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable. + NSLog(@"%@", oneDecNum); // prints => 10.99 as NSDecimalNumber is immutable // BOOL literals NSNumber *yesNumber = @YES; @@ -125,12 +125,12 @@ int main (int argc, const char * argv[]) NSLog(@"%i", yesBool); // prints => 1 // Array object - // May contain different data types, but must be an Objective-C object. + // May contain different data types, but must be an Objective-C object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" // NSMutableArray is mutable version of NSArray allowing to change items in array - // and extend or shrink array object. Convenient, but not as efficient as NSArray. + // and extend or shrink array object. Convenient, but not as efficient as NSArray NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; [mutableArray addObject:@"World"]; @@ -141,7 +141,7 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // Print "Object = (null)" - // NSMutableDictionary also available as a mutable dictionary object. + // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; [mutableDictionary setObject:@"value2" forKey:@"key2"]; @@ -150,7 +150,7 @@ int main (int argc, const char * argv[]) // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) - // NSMutableSet also available as a mutable set object. + // NSMutableSet also available as a mutable set object NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; [mutableSet addObject:@"Hello"]; @@ -209,7 +209,7 @@ int main (int argc, const char * argv[]) int ii = 0; while (ii < 4) { - NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value. + NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value } // => prints "0," // "1," // "2," @@ -235,7 +235,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Object for loop statement. Can be used with any Objective-C object type. + // Object for loop statement. Can be used with any Objective-C object type for (id item in values) { NSLog(@"%@,", item); } // => prints "0," @@ -262,19 +262,19 @@ int main (int argc, const char * argv[]) // Objects /////////////////////////////////////// - // Create an object instance by allocating memory and initializing it. - // An object is not fully functional until both steps have been completed. + // Create an object instance by allocating memory and initializing it + // An object is not fully functional until both steps have been completed MyClass *myObject = [[MyClass alloc] init]; // The Objective-C model of object-oriented programming is based on message - // passing to object instances. - // In Objective-C one does not simply call a method; one sends a message. + // passing to object instances + // In Objective-C one does not simply call a method; one sends a message [myObject instanceMethodWithParameter:@"Steve Jobs"]; // Clean up the memory you used into your program [pool drain]; - // End of @autoreleasepool. + // End of @autoreleasepool } // End the program @@ -291,22 +291,22 @@ int main (int argc, const char * argv[]) // { // type name; <= variable declarations; // } -// @property type name; <= property declarations. -// -/+ (type) Method declarations; <= Method declarations. +// @property type name; <= property declarations +// -/+ (type) Method declarations; <= Method declarations // @end @interface MyClass : NSObject // NSObject is Objective-C's base object class. { - // Instance variable declarations (can exist in either interface or implementation file). + // Instance variable declarations (can exist in either interface or implementation file) int count; // Protected access by default. - @private id data; // Private access. (More convenient to declare in implementation file). + @private id data; // Private access (More convenient to declare in implementation file) NSString *name; } -// Convenient notation for public access variables to auto generate a setter method. -// By default, setter method name is 'set' followed by @property variable name. +// Convenient notation for public access variables to auto generate a setter method +// By default, setter method name is 'set' followed by @property variable name @property int propInt; // Setter method name = 'setPropInt' -@property (copy) id copyId; // (copy) => Copy the object during assignment. -// (readonly) => Cannot set value outside @interface. -@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor. +@property (copy) id copyId; // (copy) => Copy the object during assignment +// (readonly) => Cannot set value outside @interface +@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; @@ -323,14 +323,14 @@ int main (int argc, const char * argv[]) // Constructor methods with arguments: - (id)initWithDistance:(int)defaultDistance; -// Objective-C method names are very descriptive. Always name methods according to their arguments. +// Objective-C method names are very descriptive. Always name methods according to their arguments -@end // States the end of the interface. +@end // States the end of the interface // To access public variables from the implementation file, @property generates a setter method // automatically. Method name is 'set' followed by @property variable name: -MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance. +MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance [myClass setCount:10]; NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: @@ -345,39 +345,39 @@ NSString *classMethodString = [MyClass classMethod]; MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; // Call instance methods: -MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance. +MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; -// Selectors. +// Selectors // Way to dynamically represent methods. Used to call methods of a class, pass methods // through functions to tell other classes they should call it, and to save methods -// as a variable. -// SEL is the data type. @selector() returns a selector from method name provided. +// as a variable +// SEL is the data type. @selector() returns a selector from method name provided // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); -if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method. - // Must put all method arguments into one object to send to performSelector function. +if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method + // Must put all method arguments into one object to send to performSelector function NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; - [myClass performSelector:selectorVar withObject:arguments]; // Calls the method. + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method } else { - // NSStringFromSelector() returns a NSString of the method name of a given selector. + // NSStringFromSelector() returns a NSString of the method name of a given selector NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); } // Implement the methods in an implementation (MyClass.m) file: @implementation MyClass { - long distance; // Private access instance variable. + long distance; // Private access instance variable NSNumber height; } // To access a public variable from the interface file, use '_' followed by variable name: -_count = 5; // References "int count" from MyClass interface. +_count = 5; // References "int count" from MyClass interface // Access variables defined in implementation file: -distance = 18; // References "long distance" from MyClass implementation. +distance = 18; // References "long distance" from MyClass implementation // To use @property variable in implementation, use @synthesize to create accessor variable: -@synthesize roString = _roString; // _roString available now in @implementation. +@synthesize roString = _roString; // _roString available now in @implementation -// Called before calling any class methods or instantiating any objects. +// Called before calling any class methods or instantiating any objects + (void)initialize { if (self == [MyClass class]) { @@ -385,20 +385,20 @@ distance = 18; // References "long distance" from MyClass implementation. } } -// Counterpart to initialize method. Called when an object's reference count is zero. +// Counterpart to initialize method. Called when an object's reference count is zero - (void)dealloc { [height release]; // If not using ARC, make sure to release class variable objects - [super dealloc]; // and call parent class dealloc. + [super dealloc]; // and call parent class dealloc } -// Constructors are a way of creating instances of a class. -// This is a default constructor which is called when the object is initialized. +// Constructors are a way of creating instances of a class +// This is a default constructor which is called when the object is initialized. - (id)init { - if ((self = [super init])) // 'super' used to access methods from parent class. + if ((self = [super init])) // 'super' used to access methods from parent class { - self.count = 1; // 'self' used for object to call itself. + self.count = 1; // 'self' used for object to call itself } return self; } @@ -430,11 +430,11 @@ distance = 18; // References "long distance" from MyClass implementation. return @42; } -// To create a private method, create the method in the @implementation but not in the @interface. +// To create a private method, create the method in the @implementation but not in the @interface - (NSNumber *)secretPrivateMethod { return @72; } -[self secretPrivateMethod]; // Calls private method. +[self secretPrivateMethod]; // Calls private method // Methods declared into MyProtocol - (void)myProtocolMethod @@ -442,7 +442,7 @@ distance = 18; // References "long distance" from MyClass implementation. // statements } -@end // States the end of the implementation. +@end // States the end of the implementation /* * A protocol declares methods that can be implemented by any class. @@ -472,34 +472,34 @@ With all object interactions, follow the pattern of: (1) create the object, (2) use the object, (3) then free the object from memory. */ -MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object. -[classVar release]; // Decrements classVar's reference count. -// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object. -MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner. -[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object. +MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object +[classVar release]; // Decrements classVar's reference count +// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object +MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner +[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object -// @property can use 'retain' and 'assign' as well for small convenient definitions. -@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference). -@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference). +// @property can use 'retain' and 'assign' as well for small convenient definitions +@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference) +@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference) // Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). // ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, -// you must not use retain, relase, or autorelease. +// you must not use retain, relase, or autorelease MyClass *arcMyClass = [[MyClass alloc] init]; // ... code using arcMyClass // Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, -// there is no need. It will insert this release statement for you. +// there is no need. It will insert this release statement for you -// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'. +// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong' @property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count -// is set to zero, weakVar will automatically receive value of nil to avoid application crashing. -@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use. +// is set to zero, weakVar will automatically receive value of nil to avoid application crashing +@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use // For regular variables (not @property declared variables), use the following: -__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope. -__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil. -__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released. +__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope +__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil +__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released ``` ## Further Reading -- cgit v1.2.3 From e3b20c7e26cdbe77932a344a19402c4431a35f92 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 21:27:42 -0600 Subject: Add categories description and Car example. --- objective-c.html.markdown | 95 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 90 insertions(+), 5 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 453a42a5..b6b378d5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -444,11 +444,96 @@ distance = 18; // References "long distance" from MyClass implementation @end // States the end of the implementation -/* - * A protocol declares methods that can be implemented by any class. - * Protocols are not classes themselves. They simply define an interface - * that other objects are responsible for implementing. - */ +// Categories +// A category is a group of methods designed to extend a class. They allow you to add new methods +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// functionality to an object. +// Categories allow you to: +// -- Add methods to an existing class for organizational purposes. +// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it +// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. + +// Here is a simple Car base class. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + +@end + +// And the simple Car base class implementation: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Car is on."); +} +- (void)accelerate { + NSLog(@"Accelerating."); +} + +@end + +// Now, if we wanted to create a Truck object, we would create a subclass of Car instead as it would +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create +// a category to add these cleaning methods: +// @interface filename: Car+Clean.h +#import "Car.h" // Make sure to import base class to extend. + +@interface Car (Clean) // The category name is inside () following the name of the base class. + +- (void)washWindows; // Names of the new methods we are adding to our Car object. +- (void)wax; + +@end + +// @implementation filename: Car+Clean.m +#import "Car+Clean.h" + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Windows washed."); +} +- (void)wax { + NSLog(@"Waxed."); +} + +@end + +// Any Car object instance has the ability to use a category. All they need to do is import it: +#import "Car+Clean.h" // Import as many different categories as you want to use. +#import "Car.h" // Also need to import base class to use it's original functionality. + +int main(int argc, const char *argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Red"; + mustang.make = @"Ford"; + + [mustang turnOn]; // Use methods from base Car class. + [mustang washWindows]; // Use methods from Car's Clean category. + } + return 0; +} + + +// Protocols +// A protocol declares methods that can be implemented by any class. +// Protocols are not classes themselves. They simply define an interface +// that other objects are responsible for implementing. @protocol MyProtocol - (void)myProtocolMethod; @end -- cgit v1.2.3 From e3853e564bea5a1463ee7b1ec4b9beaaae295d0c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 21:55:20 -0600 Subject: Add description and example of how to simulate protected methods. --- objective-c.html.markdown | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index b6b378d5..33200b63 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -430,7 +430,12 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } +<<<<<<< HEAD // To create a private method, create the method in the @implementation but not in the @interface +======= +// Objective-C does not have private method declarations, but you can simulate them. +// To simulate a private method, create the method in the @implementation but not in the @interface. +>>>>>>> 421f48c... Add description and example of how to simulate protected methods. - (NSNumber *)secretPrivateMethod { return @72; } @@ -485,11 +490,11 @@ distance = 18; // References "long distance" from MyClass implementation @end -// Now, if we wanted to create a Truck object, we would create a subclass of Car instead as it would +// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would // be changing the functionality of the Car to behave like a truck. But lets say we want to just add // functionality to this existing Car. A good example would be to clean the car. So we would create // a category to add these cleaning methods: -// @interface filename: Car+Clean.h +// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) #import "Car.h" // Make sure to import base class to extend. @interface Car (Clean) // The category name is inside () following the name of the base class. @@ -499,8 +504,8 @@ distance = 18; // References "long distance" from MyClass implementation @end -// @implementation filename: Car+Clean.m -#import "Car+Clean.h" +// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m) +#import "Car+Clean.h" // Import the Clean category's @interface file. @implementation Car (Clean) @@ -511,13 +516,13 @@ distance = 18; // References "long distance" from MyClass implementation NSLog(@"Waxed."); } -@end +@end // Any Car object instance has the ability to use a category. All they need to do is import it: #import "Car+Clean.h" // Import as many different categories as you want to use. #import "Car.h" // Also need to import base class to use it's original functionality. -int main(int argc, const char *argv[]) { +int main (int argc, const char * argv[]) { @autoreleasepool { Car *mustang = [[Car alloc] init]; mustang.color = @"Red"; @@ -529,6 +534,24 @@ int main(int argc, const char *argv[]) { return 0; } +// Objective-C does not have protected method declarations but you can simulate them. +// Create a category containing all of the protected methods, then import it ONLY into the +// @implementation file of a class belonging to the Car class: +@interface Car (Protected) // Naming category 'Protected' to remember methods are protected. + +- (void)lockCar; // Methods listed here may only be created by Car objects. + +@end +//To use protected methods, import the category, then implement the methods: +#import "Car+Protected.h" // Remember, import in the @implementation file only. + +@implementation Car + +- (void)lockCar { + NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. +} + +@end // Protocols // A protocol declares methods that can be implemented by any class. -- cgit v1.2.3 From 4b44b03a07bf6ffc1f265fa0f08e8ef8ceeae8d3 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 23:37:43 -0600 Subject: Add extensions description with example. --- objective-c.html.markdown | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 33200b63..47af5ae8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -553,6 +553,42 @@ int main (int argc, const char * argv[]) { @end +// Extensions +// Extensions allow you to override public access property attributes and methods of an @interface. +// @interface filename: Shape.h +@interface Shape : NSObject // Base Shape class extension overrides below. + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// You can override numOfSides variable or getNumOfSides method to edit them with an extension: +// @implementation filename: Shape.m +#import "Shape.h" +// Extensions live in the same file as the class @implementation. +@interface Shape () // () after base class name declares an extension. + +@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly. +-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int. +-(void)privateMethod; // You can also create new private methods inside of extensions. + +@end +// The main @implementation: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // All statements inside of extension must be in the @implementation. + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Private method created by extension. Shape instances cannot call me."); +} + +@end + + // Protocols // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface -- cgit v1.2.3 From 57c16ffb5ca3c91d163479f3d0d6eaddf51fb123 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 9 Jan 2014 19:56:23 -0600 Subject: Add much more to the protocols section. --- objective-c.html.markdown | 74 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 67 insertions(+), 7 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 47af5ae8..781cdd3e 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -430,12 +430,8 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } -<<<<<<< HEAD -// To create a private method, create the method in the @implementation but not in the @interface -======= // Objective-C does not have private method declarations, but you can simulate them. // To simulate a private method, create the method in the @implementation but not in the @interface. ->>>>>>> 421f48c... Add description and example of how to simulate protected methods. - (NSNumber *)secretPrivateMethod { return @72; } @@ -449,7 +445,9 @@ distance = 18; // References "long distance" from MyClass implementation @end // States the end of the implementation +/////////////////////////////////////// // Categories +/////////////////////////////////////// // A category is a group of methods designed to extend a class. They allow you to add new methods // to an existing class for organizational purposes. This is not to be mistaken with subclasses. // Subclasses are meant to CHANGE functionality of an object while categories instead ADD @@ -553,7 +551,9 @@ int main (int argc, const char * argv[]) { @end +/////////////////////////////////////// // Extensions +/////////////////////////////////////// // Extensions allow you to override public access property attributes and methods of an @interface. // @interface filename: Shape.h @interface Shape : NSObject // Base Shape class extension overrides below. @@ -588,15 +588,75 @@ int main (int argc, const char * argv[]) { @end - +/////////////////////////////////////// // Protocols +/////////////////////////////////////// // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface // that other objects are responsible for implementing. -@protocol MyProtocol - - (void)myProtocolMethod; + // @protocol filename: "CarUtilities.h" +@protocol CarUtilities // => Name of another protocol this protocol includes. + @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and + - (void)turnOnEngine; // all defined methods. +@end +// Below is an example class implementing the protocol. +#import "CarUtilities.h" // Import the @protocol file. + +@interface Car : NSObject // Name of protocol goes inside <> + // You don't need the @property or method names here for CarUtilities. Only @implementation does. +- (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. +@end +// The @implementation needs to implement the @properties and methods for the protocol. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. + +- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define + _engineOn = YES; // how you implement a method, it just requires that you do implement it. +} +// You may use a protocol as data as you know what methods and variables it has implemented. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // You have access to object variables + [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. +} + @end +// Instances of Car now have access to the protocol. +Car *carInstance = [[Car alloc] init]; +[[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // prints => "Car engine is on." +} +// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Categories may implement protocols as well: @interface Car (CarCategory) +// You may implement many protocols: @interface Car : NSObject +// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: +#import "Brother.h" + +@protocol Brother; // Forward-declare statement. Without it, compiler would through error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; +@end +// See the problem is that Sister relies on Brother, and Brother relies on Sister. +#import "Sister.h" + +@protocol Sister; // These lines stop the recursion, resolving the issue. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end /////////////////////////////////////// // Memory Management -- cgit v1.2.3 From 4a9b80d5f5a0b2618bf7b7f5b4a6b603f6f7d7f0 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 29 Jan 2014 22:05:08 -0800 Subject: No objc highlighting, use cpp to fix errors --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 453a42a5..6f48c155 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```objective-c +```cpp // Single-line comments start with // /* -- cgit v1.2.3 From 25fb918e9c0ef62205de86321d503aabf250f60a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 8 Jan 2014 21:27:42 -0600 Subject: Merge with master. --- objective-c.html.markdown | 195 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 191 insertions(+), 4 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0f0165ec..59169b16 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -249,14 +249,17 @@ int main (int argc, const char * argv[]) // Your statements here @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) + } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. { NSLog(@"Exception: %@", e); } @finally { - NSLog(@"Finally"); + NSLog(@"Finally. Time to clean up."); } // => prints "Exception: File Not Found on System" - // "Finally" + // "Finally. Time to clean up." + + // NSError objects are useful for function arguments to populate on user mistakes. + NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; /////////////////////////////////////// // Objects @@ -549,6 +552,116 @@ int main (int argc, const char * argv[]) { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. } +// Categories +// A category is a group of methods designed to extend a class. They allow you to add new methods +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// functionality to an object. +// Categories allow you to: +// -- Add methods to an existing class for organizational purposes. +// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it +// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. + +// Here is a simple Car base class. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + +@end + +// And the simple Car base class implementation: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Car is on."); +} +- (void)accelerate { + NSLog(@"Accelerating."); +} + +@end + +// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create +// a category to add these cleaning methods: +// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) +#import "Car.h" // Make sure to import base class to extend. + +@interface Car (Clean) // The category name is inside () following the name of the base class. + +- (void)washWindows; // Names of the new methods we are adding to our Car object. +- (void)wax; + +@end + +// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m) +#import "Car+Clean.h" // Import the Clean category's @interface file. + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Windows washed."); +} +- (void)wax { + NSLog(@"Waxed."); +} + +@end + +// Any Car object instance has the ability to use a category. All they need to do is import it: +#import "Car+Clean.h" // Import as many different categories as you want to use. +#import "Car.h" // Also need to import base class to use it's original functionality. + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Red"; + mustang.make = @"Ford"; + + [mustang turnOn]; // Use methods from base Car class. + [mustang washWindows]; // Use methods from Car's Clean category. + } + return 0; +} + +// Objective-C does not have protected method declarations but you can simulate them. +// Create a category containing all of the protected methods, then import it ONLY into the +// @implementation file of a class belonging to the Car class: +@interface Car (Protected) // Naming category 'Protected' to remember methods are protected. + +- (void)lockCar; // Methods listed here may only be created by Car objects. + +@end +//To use protected methods, import the category, then implement the methods: +#import "Car+Protected.h" // Remember, import in the @implementation file only. + +@implementation Car + +- (void)lockCar { + NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. +} + +@end + +// Protocols +// A protocol declares methods that can be implemented by any class. +// Protocols are not classes themselves. They simply define an interface +// that other objects are responsible for implementing. +@protocol MyProtocol + - (void)myProtocolMethod; @end /////////////////////////////////////// @@ -594,7 +707,7 @@ int main (int argc, const char * argv[]) { // A protocol declares methods that can be implemented by any class. // Protocols are not classes themselves. They simply define an interface // that other objects are responsible for implementing. - // @protocol filename: "CarUtilities.h" +// @protocol filename: "CarUtilities.h" @protocol CarUtilities // => Name of another protocol this protocol includes. @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and - (void)turnOnEngine; // all defined methods. @@ -605,6 +718,7 @@ int main (int argc, const char * argv[]) { @interface Car : NSObject // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. +<<<<<<< HEAD @end // The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @@ -646,6 +760,49 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; +======= +@end +// The @implementation needs to implement the @properties and methods for the protocol. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. + +- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define + _engineOn = YES; // how you implement a method, it just requires that you do implement it. +} +// You may use a protocol as data as you know what methods and variables it has implemented. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // You have access to object variables + [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. +} + +@end +// Instances of Car now have access to the protocol. +Car *carInstance = [[Car alloc] init]; +[[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // prints => "Car engine is on." +} +// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Categories may implement protocols as well: @interface Car (CarCategory) +// You may implement many protocols: @interface Car : NSObject +// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: +#import "Brother.h" + +@protocol Brother; // Forward-declare statement. Without it, compiler would through error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; + +>>>>>>> 8c6f583... Add much more to the protocols section. @end // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" @@ -658,6 +815,36 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { @end + +/////////////////////////////////////// +// Blocks +/////////////////////////////////////// +// Blocks are statements of code, just like a function, that is able to be used as data. +// Below is a simple block with an integer argument that returns the argument plus 4. +int (^addUp)(int n); // Declare a variable to store the block. +void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. +// Blocks have access to variables in the same scope. But the variables are readonly and the +// value passed to the block is the value of the variable when the block is created. +int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17. +__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar. +addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. + NSLog(@"You may have as many lines in a block as you would like."); + NSSet *blockSet; // Also, you can declare local variables. + mutableVar = 32; // Assigning new value to __block variable. + return n + outsideVar; // Return statements are optional. +} +int addUp = add(10 + 16); // Calls block code with arguments. +// Blocks are often used as arguments to functions to be called later, or for callbacks. +@implementation BlockExample : NSObject + + - (void)runBlock:(void (^)(NSString))block { + NSLog(@"Block argument returns nothing and takes in a NSString object."); + block(@"Argument given to block to execute."); // Calling block. + } + + @end + + /////////////////////////////////////// // Memory Management /////////////////////////////////////// -- cgit v1.2.3 From dcf7cd620d9e957d384e143eb2fb2cca7351cfae Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Fri, 10 Jan 2014 22:58:45 -0600 Subject: Add to exceptions section. Add NSError reference. --- objective-c.html.markdown | 3 --- 1 file changed, 3 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 59169b16..348a72d5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -718,7 +718,6 @@ int main (int argc, const char * argv[]) { @interface Car : NSObject // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. -<<<<<<< HEAD @end // The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @@ -760,7 +759,6 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; -======= @end // The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @@ -802,7 +800,6 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; ->>>>>>> 8c6f583... Add much more to the protocols section. @end // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" -- cgit v1.2.3 From 58bd9cbdaf97955fab0b6a0ae1f0827f84abdefa Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Wed, 19 Mar 2014 12:39:07 -0500 Subject: Remove duplicate Categories section. Fix small typo. --- objective-c.html.markdown | 152 +--------------------------------------------- 1 file changed, 1 insertion(+), 151 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 348a72d5..772e72ca 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -552,116 +552,6 @@ int main (int argc, const char * argv[]) { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. } -// Categories -// A category is a group of methods designed to extend a class. They allow you to add new methods -// to an existing class for organizational purposes. This is not to be mistaken with subclasses. -// Subclasses are meant to CHANGE functionality of an object while categories instead ADD -// functionality to an object. -// Categories allow you to: -// -- Add methods to an existing class for organizational purposes. -// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. -// -- Add ability to create protected and private methods to classes. -// NOTE: Do not override methods of the base class in a category even though you have the ability -// to. Overriding methods may cause compiler errors later between different categories and it -// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. - -// Here is a simple Car base class. -@interface Car : NSObject - -@property NSString *make; -@property NSString *color; - -- (void)turnOn; -- (void)accelerate; - -@end - -// And the simple Car base class implementation: -#import "Car.h" - -@implementation Car - -@synthesize make = _make; -@synthesize color = _color; - -- (void)turnOn { - NSLog(@"Car is on."); -} -- (void)accelerate { - NSLog(@"Accelerating."); -} - -@end - -// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would -// be changing the functionality of the Car to behave like a truck. But lets say we want to just add -// functionality to this existing Car. A good example would be to clean the car. So we would create -// a category to add these cleaning methods: -// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) -#import "Car.h" // Make sure to import base class to extend. - -@interface Car (Clean) // The category name is inside () following the name of the base class. - -- (void)washWindows; // Names of the new methods we are adding to our Car object. -- (void)wax; - -@end - -// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m) -#import "Car+Clean.h" // Import the Clean category's @interface file. - -@implementation Car (Clean) - -- (void)washWindows { - NSLog(@"Windows washed."); -} -- (void)wax { - NSLog(@"Waxed."); -} - -@end - -// Any Car object instance has the ability to use a category. All they need to do is import it: -#import "Car+Clean.h" // Import as many different categories as you want to use. -#import "Car.h" // Also need to import base class to use it's original functionality. - -int main (int argc, const char * argv[]) { - @autoreleasepool { - Car *mustang = [[Car alloc] init]; - mustang.color = @"Red"; - mustang.make = @"Ford"; - - [mustang turnOn]; // Use methods from base Car class. - [mustang washWindows]; // Use methods from Car's Clean category. - } - return 0; -} - -// Objective-C does not have protected method declarations but you can simulate them. -// Create a category containing all of the protected methods, then import it ONLY into the -// @implementation file of a class belonging to the Car class: -@interface Car (Protected) // Naming category 'Protected' to remember methods are protected. - -- (void)lockCar; // Methods listed here may only be created by Car objects. - -@end -//To use protected methods, import the category, then implement the methods: -#import "Car+Protected.h" // Remember, import in the @implementation file only. - -@implementation Car - -- (void)lockCar { - NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. -} - -@end - -// Protocols -// A protocol declares methods that can be implemented by any class. -// Protocols are not classes themselves. They simply define an interface -// that other objects are responsible for implementing. -@protocol MyProtocol - - (void)myProtocolMethod; @end /////////////////////////////////////// @@ -760,47 +650,7 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - (void)beNiceToBrother:(id )brother; @end -// The @implementation needs to implement the @properties and methods for the protocol. -@implementation Car : NSObject - -@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. - -- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define - _engineOn = YES; // how you implement a method, it just requires that you do implement it. -} -// You may use a protocol as data as you know what methods and variables it has implemented. -- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { - [objectOfSomeKind engineOn]; // You have access to object variables - [objectOfSomeKind turnOnEngine]; // and the methods inside. - [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. -} - -@end -// Instances of Car now have access to the protocol. -Car *carInstance = [[Car alloc] init]; -[[carInstance setEngineOn:NO]; -[carInstance turnOnEngine]; -if ([carInstance engineOn]) { - NSLog(@"Car engine is on."); // prints => "Car engine is on." -} -// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods: -if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { - NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); -} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { - NSLog(@"This does run as the Car class implements the CarUtilities protocol."); -} -// Categories may implement protocols as well: @interface Car (CarCategory) -// You may implement many protocols: @interface Car : NSObject -// NOTE: If two or more protocols rely on each other, make sure to forward-declare them: -#import "Brother.h" -@protocol Brother; // Forward-declare statement. Without it, compiler would through error. - -@protocol Sister - -- (void)beNiceToBrother:(id )brother; - -@end // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" @@ -816,7 +666,7 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Blocks /////////////////////////////////////// -// Blocks are statements of code, just like a function, that is able to be used as data. +// Blocks are statements of code, just like a function, that are able to be used as data. // Below is a simple block with an integer argument that returns the argument plus 4. int (^addUp)(int n); // Declare a variable to store the block. void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. -- cgit v1.2.3 From eab554a7a7f2869ff7dac9f54acce9a7ed55cfa4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 8 Sep 2014 13:08:28 +0200 Subject: Review docs for added rouge lexers and update those with new highlighters --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 772e72ca..caad49a5 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC.m Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```cpp +```objective_c // Single-line comments start with // /* -- cgit v1.2.3 From df0dbef198f810d976a76cfb4453d9c99ac2b360 Mon Sep 17 00:00:00 2001 From: Nicholas Hrynuik Date: Sat, 31 Jan 2015 21:38:24 -0500 Subject: Fix typos in objective-c doc --- objective-c.html.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index caad49a5..bac8fb55 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -55,7 +55,7 @@ int main (int argc, const char * argv[]) id myObject2 = nil; // Weak typing // %@ is an object // 'description' is a convention to display the value of the Objects - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints "(null) and (null)" // String NSString *worldString = @"World"; @@ -70,7 +70,7 @@ int main (int argc, const char * argv[]) char theLetterZ = [theLetterZNumber charValue]; // or 'Z' NSLog(@"%c", theLetterZ); - // Integral literals + // Integer literals NSNumber *fortyTwoNumber = @42; int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); @@ -128,9 +128,10 @@ int main (int argc, const char * argv[]) // May contain different data types, but must be an Objective-C object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" - // NSMutableArray is mutable version of NSArray allowing to change items in array - // and extend or shrink array object. Convenient, but not as efficient as NSArray + NSLog(@"Third number = %@", thirdNumber); // prints "Third number = 3" + // NSMutableArray is a mutable version of NSArray allowing you to change + // items in array and extend or shrink array object. Convenient, but not + // as efficient as NSArray NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; [mutableArray addObject:@"World"]; @@ -140,7 +141,7 @@ int main (int argc, const char * argv[]) // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + NSLog(@"Object = %@", valueObject); // prints "Object = (null)" // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; @@ -627,7 +628,7 @@ int main (int argc, const char * argv[]) { @end // Instances of Car now have access to the protocol. Car *carInstance = [[Car alloc] init]; -[[carInstance setEngineOn:NO]; +[carInstance setEngineOn:NO]; [carInstance turnOnEngine]; if ([carInstance engineOn]) { NSLog(@"Car engine is on."); // prints => "Car engine is on." -- cgit v1.2.3 From d406057dc78ef128186ce9b059b04120e21f39b8 Mon Sep 17 00:00:00 2001 From: Nicholas Hrynuik Date: Sat, 31 Jan 2015 22:18:02 -0500 Subject: Further fix of typos in objective-c doc --- objective-c.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index bac8fb55..56640a87 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -55,7 +55,7 @@ int main (int argc, const char * argv[]) id myObject2 = nil; // Weak typing // %@ is an object // 'description' is a convention to display the value of the Objects - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints "(null) and (null)" + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)" // String NSString *worldString = @"World"; @@ -70,7 +70,7 @@ int main (int argc, const char * argv[]) char theLetterZ = [theLetterZNumber charValue]; // or 'Z' NSLog(@"%c", theLetterZ); - // Integer literals + // Integral literals NSNumber *fortyTwoNumber = @42; int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); @@ -128,10 +128,10 @@ int main (int argc, const char * argv[]) // May contain different data types, but must be an Objective-C object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // prints "Third number = 3" - // NSMutableArray is a mutable version of NSArray allowing you to change - // items in array and extend or shrink array object. Convenient, but not - // as efficient as NSArray + NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" + // NSMutableArray is a mutable version of NSArray, allowing you to change + // the items in the array and to extend or shrink the array object. + // Convenient, but not as efficient as NSArray. NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; [mutableArray addObject:@"World"]; @@ -141,7 +141,7 @@ int main (int argc, const char * argv[]) // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // prints "Object = (null)" + NSLog(@"Object = %@", valueObject); // prints => "Object = (null)" // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; @@ -211,7 +211,7 @@ int main (int argc, const char * argv[]) while (ii < 4) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," @@ -221,7 +221,7 @@ int main (int argc, const char * argv[]) for (jj=0; jj < 4; jj++) { NSLog(@"%d,", jj); - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," @@ -231,7 +231,7 @@ int main (int argc, const char * argv[]) for (NSNumber *value in values) { NSLog(@"%@,", value); - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," @@ -239,7 +239,7 @@ int main (int argc, const char * argv[]) // Object for loop statement. Can be used with any Objective-C object type for (id item in values) { NSLog(@"%@,", item); - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," @@ -256,7 +256,7 @@ int main (int argc, const char * argv[]) } @finally { NSLog(@"Finally. Time to clean up."); - } // => prints "Exception: File Not Found on System" + } // prints => "Exception: File Not Found on System" // "Finally. Time to clean up." // NSError objects are useful for function arguments to populate on user mistakes. -- cgit v1.2.3 From 27b9ee85fb65c9192a070890375e678a7d02f9e6 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 12 Aug 2015 06:38:17 +0900 Subject: Fixes #1196 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 56640a87..91b84b47 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -415,7 +415,7 @@ distance = 18; // References "long distance" from MyClass implementation + (NSString *)classMethod { - return [[self alloc] init]; + return @"Some string"; } + (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight -- cgit v1.2.3 From f53f50aad135025cae04ff9b28f6bf11c8e45bfd Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Tue, 6 Oct 2015 23:06:21 -0400 Subject: Added additional reading for both iOS and OS X for Objective-C from Apple Developer site. Added contribution line. --- objective-c.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 91b84b47..407ba3c8 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] - ["Levi Bostian", "https://github.com/levibostian"] + - ["Clayton Walker", "https://github.com/cwalk"] filename: LearnObjectiveC.m --- @@ -747,4 +748,8 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not se [Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) +[Programming with Objective-C for iOS](https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html) + +[Programming with Objective-C for Mac OSX](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) + [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 960ee4a1856db8eadb96277bb2422edfa8f2a81c Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Wed, 7 Oct 2015 23:11:24 -0400 Subject: removing whitespace all over --- objective-c.html.markdown | 158 +++++++++++++++++++++++----------------------- 1 file changed, 79 insertions(+), 79 deletions(-) (limited to 'objective-c.html.markdown') diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 407ba3c8..89901308 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -11,7 +11,7 @@ filename: LearnObjectiveC.m --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. -It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. +It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. ```objective_c // Single-line comments start with // @@ -41,15 +41,15 @@ int main (int argc, const char * argv[]) // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" - + /////////////////////////////////////// // Types & Variables /////////////////////////////////////// - + // Primitive declarations int myPrimitive1 = 1; long myPrimitive2 = 234554664565; - + // Object declarations // Put the * in front of the variable names for strongly-typed object declarations MyClass *myObject1 = nil; // Strong typing @@ -57,15 +57,15 @@ int main (int argc, const char * argv[]) // %@ is an object // 'description' is a convention to display the value of the Objects NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)" - + // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" // NSMutableString is a mutable version of the NSString object NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" - + // Character literals NSNumber *theLetterZNumber = @'Z'; char theLetterZ = [theLetterZNumber charValue]; // or 'Z' @@ -75,11 +75,11 @@ int main (int argc, const char * argv[]) NSNumber *fortyTwoNumber = @42; int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); - + NSNumber *fortyTwoUnsignedNumber = @42U; unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 NSLog(@"%u", fortyTwoUnsigned); - + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); @@ -87,7 +87,7 @@ int main (int argc, const char * argv[]) NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41 NSLog(@"%u", fortyOneUnsigned); - + NSNumber *fortyTwoLongNumber = @42L; long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); @@ -101,7 +101,7 @@ int main (int argc, const char * argv[]) float piFloat = [piFloatNumber floatValue]; // or 3.141592654f NSLog(@"%f", piFloat); // prints => 3.141592654 NSLog(@"%5.2f", piFloat); // prints => " 3.14" - + NSNumber *piDoubleNumber = @3.1415926535; double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); @@ -111,7 +111,7 @@ int main (int argc, const char * argv[]) NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: - [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberByAdding:twoDecNum]; [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; @@ -130,8 +130,8 @@ int main (int argc, const char * argv[]) NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" - // NSMutableArray is a mutable version of NSArray, allowing you to change - // the items in the array and to extend or shrink the array object. + // NSMutableArray is a mutable version of NSArray, allowing you to change + // the items in the array and to extend or shrink the array object. // Convenient, but not as efficient as NSArray. NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; @@ -161,7 +161,7 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Operators /////////////////////////////////////// - + // The operators works like in the C language // For example: 2 + 5; // => 7 @@ -206,13 +206,13 @@ int main (int argc, const char * argv[]) NSLog(@"I print"); } break; } - + // While loops statements int ii = 0; while (ii < 4) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value - } // prints => "0," + } // prints => "0," // "1," // "2," // "3," @@ -222,25 +222,25 @@ int main (int argc, const char * argv[]) for (jj=0; jj < 4; jj++) { NSLog(@"%d,", jj); - } // prints => "0," + } // prints => "0," // "1," // "2," // "3," - - // Foreach statements + + // Foreach statements NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { NSLog(@"%@,", value); - } // prints => "0," + } // prints => "0," // "1," // "2," // "3," // Object for loop statement. Can be used with any Objective-C object type - for (id item in values) { - NSLog(@"%@,", item); - } // prints => "0," + for (id item in values) { + NSLog(@"%@,", item); + } // prints => "0," // "1," // "2," // "3," @@ -251,7 +251,7 @@ int main (int argc, const char * argv[]) // Your statements here @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. + } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. { NSLog(@"Exception: %@", e); } @finally @@ -260,17 +260,17 @@ int main (int argc, const char * argv[]) } // prints => "Exception: File Not Found on System" // "Finally. Time to clean up." - // NSError objects are useful for function arguments to populate on user mistakes. + // NSError objects are useful for function arguments to populate on user mistakes. NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; - + /////////////////////////////////////// // Objects /////////////////////////////////////// - + // Create an object instance by allocating memory and initializing it // An object is not fully functional until both steps have been completed MyClass *myObject = [[MyClass alloc] init]; - + // The Objective-C model of object-oriented programming is based on message // passing to object instances // In Objective-C one does not simply call a method; one sends a message @@ -281,7 +281,7 @@ int main (int argc, const char * argv[]) // End of @autoreleasepool } - + // End the program return 0; } @@ -302,9 +302,9 @@ int main (int argc, const char * argv[]) @interface MyClass : NSObject // NSObject is Objective-C's base object class. { // Instance variable declarations (can exist in either interface or implementation file) - int count; // Protected access by default. + int count; // Protected access by default. @private id data; // Private access (More convenient to declare in implementation file) - NSString *name; + NSString *name; } // Convenient notation for public access variables to auto generate a setter method // By default, setter method name is 'set' followed by @property variable name @@ -314,7 +314,7 @@ int main (int argc, const char * argv[]) @property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; - + // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -336,7 +336,7 @@ int main (int argc, const char * argv[]) // To access public variables from the implementation file, @property generates a setter method // automatically. Method name is 'set' followed by @property variable name: MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance -[myClass setCount:10]; +[myClass setCount:10]; NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: [myClass lengthSet:32]; @@ -359,7 +359,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell // as a variable // SEL is the data type. @selector() returns a selector from method name provided // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass -SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method // Must put all method arguments into one object to send to performSelector function NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; @@ -383,7 +383,7 @@ distance = 18; // References "long distance" from MyClass implementation @synthesize roString = _roString; // _roString available now in @implementation // Called before calling any class methods or instantiating any objects -+ (void)initialize ++ (void)initialize { if (self == [MyClass class]) { distance = 0; @@ -393,7 +393,7 @@ distance = 18; // References "long distance" from MyClass implementation // Counterpart to initialize method. Called when an object's reference count is zero - (void)dealloc { - [height release]; // If not using ARC, make sure to release class variable objects + [height release]; // If not using ARC, make sure to release class variable objects [super dealloc]; // and call parent class dealloc } @@ -408,7 +408,7 @@ distance = 18; // References "long distance" from MyClass implementation return self; } // Can create constructors that contain arguments: -- (id)initWithDistance:(int)defaultDistance +- (id)initWithDistance:(int)defaultDistance { distance = defaultDistance; return self; @@ -419,7 +419,7 @@ distance = 18; // References "long distance" from MyClass implementation return @"Some string"; } -+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight { height = defaultHeight; return [[self alloc] init]; @@ -435,7 +435,7 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } -// Objective-C does not have private method declarations, but you can simulate them. +// Objective-C does not have private method declarations, but you can simulate them. // To simulate a private method, create the method in the @implementation but not in the @interface. - (NSNumber *)secretPrivateMethod { return @72; @@ -454,15 +454,15 @@ distance = 18; // References "long distance" from MyClass implementation // Categories /////////////////////////////////////// // A category is a group of methods designed to extend a class. They allow you to add new methods -// to an existing class for organizational purposes. This is not to be mistaken with subclasses. -// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD // functionality to an object. // Categories allow you to: // -- Add methods to an existing class for organizational purposes. // -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. -// -- Add ability to create protected and private methods to classes. -// NOTE: Do not override methods of the base class in a category even though you have the ability -// to. Overriding methods may cause compiler errors later between different categories and it +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it // ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. // Here is a simple Car base class. @@ -494,8 +494,8 @@ distance = 18; // References "long distance" from MyClass implementation @end // Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would -// be changing the functionality of the Car to behave like a truck. But lets say we want to just add -// functionality to this existing Car. A good example would be to clean the car. So we would create +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create // a category to add these cleaning methods: // @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) #import "Car.h" // Make sure to import base class to extend. @@ -519,7 +519,7 @@ distance = 18; // References "long distance" from MyClass implementation NSLog(@"Waxed."); } -@end +@end // Any Car object instance has the ability to use a category. All they need to do is import it: #import "Car+Clean.h" // Import as many different categories as you want to use. @@ -534,7 +534,7 @@ int main (int argc, const char * argv[]) { [mustang turnOn]; // Use methods from base Car class. [mustang washWindows]; // Use methods from Car's Clean category. } - return 0; + return 0; } // Objective-C does not have protected method declarations but you can simulate them. @@ -548,7 +548,7 @@ int main (int argc, const char * argv[]) { //To use protected methods, import the category, then implement the methods: #import "Car+Protected.h" // Remember, import in the @implementation file only. -@implementation Car +@implementation Car - (void)lockCar { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. @@ -571,8 +571,8 @@ int main (int argc, const char * argv[]) { // You can override numOfSides variable or getNumOfSides method to edit them with an extension: // @implementation filename: Shape.m #import "Shape.h" -// Extensions live in the same file as the class @implementation. -@interface Shape () // () after base class name declares an extension. +// Extensions live in the same file as the class @implementation. +@interface Shape () // () after base class name declares an extension. @property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly. -(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int. @@ -580,7 +580,7 @@ int main (int argc, const char * argv[]) { @end // The main @implementation: -@implementation Shape +@implementation Shape @synthesize numOfSides = _numOfSides; @@ -604,14 +604,14 @@ int main (int argc, const char * argv[]) { @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and - (void)turnOnEngine; // all defined methods. @end -// Below is an example class implementing the protocol. +// Below is an example class implementing the protocol. #import "CarUtilities.h" // Import the @protocol file. @interface Car : NSObject // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id )car; // You can use protocols as data too. @end -// The @implementation needs to implement the @properties and methods for the protocol. +// The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject @synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. @@ -620,14 +620,14 @@ int main (int argc, const char * argv[]) { _engineOn = YES; // how you implement a method, it just requires that you do implement it. } // You may use a protocol as data as you know what methods and variables it has implemented. -- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { [objectOfSomeKind engineOn]; // You have access to object variables - [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind turnOnEngine]; // and the methods inside. [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. } @end -// Instances of Car now have access to the protocol. +// Instances of Car now have access to the protocol. Car *carInstance = [[Car alloc] init]; [carInstance setEngineOn:NO]; [carInstance turnOnEngine]; @@ -656,10 +656,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" -@protocol Sister; // These lines stop the recursion, resolving the issue. +@protocol Sister; // These lines stop the recursion, resolving the issue. @protocol Brother - + - (void)beNiceToSister:(id )sister; @end @@ -668,24 +668,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Blocks /////////////////////////////////////// -// Blocks are statements of code, just like a function, that are able to be used as data. +// Blocks are statements of code, just like a function, that are able to be used as data. // Below is a simple block with an integer argument that returns the argument plus 4. -int (^addUp)(int n); // Declare a variable to store the block. -void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. +int (^addUp)(int n); // Declare a variable to store the block. +void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. // Blocks have access to variables in the same scope. But the variables are readonly and the -// value passed to the block is the value of the variable when the block is created. +// value passed to the block is the value of the variable when the block is created. int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17. __block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar. -addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. +addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. NSLog(@"You may have as many lines in a block as you would like."); NSSet *blockSet; // Also, you can declare local variables. mutableVar = 32; // Assigning new value to __block variable. - return n + outsideVar; // Return statements are optional. + return n + outsideVar; // Return statements are optional. } -int addUp = add(10 + 16); // Calls block code with arguments. +int addUp = add(10 + 16); // Calls block code with arguments. // Blocks are often used as arguments to functions to be called later, or for callbacks. -@implementation BlockExample : NSObject - +@implementation BlockExample : NSObject + - (void)runBlock:(void (^)(NSString))block { NSLog(@"Block argument returns nothing and takes in a NSString object."); block(@"Argument given to block to execute."); // Calling block. @@ -697,19 +697,19 @@ int addUp = add(10 + 16); // Calls block code with arguments. /////////////////////////////////////// // Memory Management /////////////////////////////////////// -/* +/* For each object used in an application, memory must be allocated for that object. When the application -is done using that object, memory must be deallocated to ensure application efficiency. -Objective-C does not use garbage collection and instead uses reference counting. As long as +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as there is at least one reference to an object (also called "owning" an object), then the object -will be available to use (known as "ownership"). +will be available to use (known as "ownership"). When an instance owns an object, its reference counter is increments by one. When the object is released, the reference counter decrements by one. When reference count is zero, -the object is removed from memory. +the object is removed from memory. -With all object interactions, follow the pattern of: -(1) create the object, (2) use the object, (3) then free the object from memory. +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. */ MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object @@ -724,11 +724,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still // Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). -// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, // you must not use retain, relase, or autorelease -MyClass *arcMyClass = [[MyClass alloc] init]; +MyClass *arcMyClass = [[MyClass alloc] init]; // ... code using arcMyClass -// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, +// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, // there is no need. It will insert this release statement for you // As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong' -- cgit v1.2.3