Guest User

Untitled

a guest
May 20th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.25 KB | None | 0 0
  1. ## Objective-C cheat sheet
  2.  
  3. //////////// Variable declarations ///////////
  4.  
  5. id anObject; // pointer to an object of any type
  6.  
  7. id anObjectMaybeNil = nil; // No object
  8.  
  9. Rectangle* rect; // pointer to an instance of Rectangle class
  10.  
  11.  
  12. //////////// Method invocation ///////////
  13.  
  14. [receiver message]; // calling "message" method on object referred to by variable "receiver"
  15.  
  16. [window setWidth:100 height:200]; // call "setWidth" method and pass parameters 100 and 200
  17.  
  18. [window setTitle:@"Window Title", "hello", 100]; // call "setTitle" with argument "Window Title" and optional args "hello" and 100
  19.  
  20.  
  21. //////////// Class definition ///////////
  22.  
  23. // importing BaseClass interface
  24. #import "BaseClass.h"
  25.  
  26. // "importing" Rectangle and Logger classes
  27. @class Rectangle, Logger;
  28.  
  29. // Declaring class Window
  30. @interface ClassExample : BaseClass // ClassExample inherited from BaseClass
  31. {
  32. // by default, all these vars are @protected
  33. float width; // instance variable
  34. Rectangle* rectangle;
  35.  
  36. @private // only this class can access these
  37. Logger* log;
  38. }
  39.  
  40. + alloc; // static or "class method"
  41. - (void)display; // instance method, no parameters
  42. - (void)setWidth:(int)width height:(int)height; // instance method with 2 parameters
  43. - (void)setTitle:(* NSString)title, ...; // instance method with 1 argument and optional arguments
  44.  
  45. @end
  46.  
  47.  
  48. //////////// Class implementation ///////////
  49.  
  50. // import class that we are defining
  51. #import "ClassExample.h"
  52.  
  53. @implementation ClassExample
  54.  
  55. + alloc {
  56. // this will be called when instance of class is created
  57. }
  58.  
  59. - (void)display {
  60. }
  61.  
  62. - (void)setWidth:(int)width height:(int)height {
  63. if ( !rectangle ) {
  64. // create new instance of Rectangle and initialize it
  65. rectangle = [[Rectangle alloc] init];
  66.  
  67. // access directly
  68. rectangle->width = width;
  69. rectangle->height = height;
  70. }
  71. }
  72.  
  73. @end
  74.  
  75.  
  76. //////////// Using classes ///////////
  77.  
  78. // Class can be interacted with as an object
  79. Class myWindowClass = [myWindow class];
  80.  
  81. // Is "myObject" an instance of class "Window"?
  82. if ( [myObject isMemberOfClass:Window]) {
  83. }
  84.  
  85. // Is "myObject" an instance of class "Window"?
  86. if ( [myObject isMemberOfClass:NSClassFromString(@"Window")]) {
  87. }
  88.  
  89. // Is "myObject" inheriting from "Window"?
  90. if ( [myObject isKindOfClass:Window]) {
  91. }
  92.  
  93. // make an instance of class Window
  94. id myWindow;
  95. myWindow = [Window alloc];
  96.  
  97.  
  98.  
  99. //////////// Class category interface ///////////
  100.  
  101. #import "ClassExample.h"
  102.  
  103. @interface ClassExample (CategoryName) // example of a category called CategoryName
  104. // no additional instance variables are allowed
  105.  
  106. - (int)countPixels;
  107.  
  108. @end
  109.  
  110.  
  111. //////////// Class category implementation ///////////
  112.  
  113. #import "ClassExample+CategoryName.h"
  114.  
  115. @implementation ClassExample (CategoryName) // implementation of methods defined in CategoryName is separate
  116.  
  117. // methods defined in categories need to be implemented separately from the main class implementation
  118.  
  119. -(int)countPixels {
  120. if ( rectangle ) {
  121. return rectangle->width * rectangle->height;
  122. }
  123.  
  124. return 0;
  125. }
  126.  
  127.  
  128. //////////// Class extensions ///////////
  129.  
  130. #import "BaseClass.h"
  131.  
  132. @class Point;
  133.  
  134. // main interface
  135. @interface ExtensionExample : BaseClass // this is the main class in this example, inherited from BaseClass
  136. {
  137. Point* center;
  138. }
  139.  
  140. - (void)setCenter:(Point*)newCenter;
  141.  
  142. @end
  143.  
  144.  
  145. // extension interface
  146. @interface ExtensionExample (Setters) // this is the extension of class ExtensionExample (or "anonymous category")
  147. // no additional instance variables are allowed
  148.  
  149. - (Point*)getCenter;
  150.  
  151. @end
  152.  
  153.  
  154. // main implementation block
  155. @implementation ExtensionExample // ALL methods need to be implemented inside of the main "implementation block"
  156.  
  157. - (void)setCenter:(Point*)newCenter // method defined inside main interface block
  158. {
  159. center = newCenter;
  160. }
  161.  
  162. - (Point*)getCenter // method defined inside extension. Implementation MUST be inside main implementation block
  163. {
  164. return center;
  165. }
  166.  
  167. @end
  168.  
  169.  
  170. //////////// PropertiesExample ///////////
  171.  
  172. @interface PropertiesExample // example of using properties
  173. {
  174. int count;
  175. NSString *name;
  176. }
  177.  
  178. @property int count; // letting compiler know that we need getter and setter for this variable
  179. @property NSString *name; // letting compiler know that we need getter and setter for this variable
  180.  
  181. @end
  182.  
  183.  
  184. // implementation
  185. @implementation PropertiesExample
  186.  
  187. @synthesize count; // compiler will automatically create getter and setter
  188.  
  189. @dynamic name; // we will create getter and setter ourselves, below
  190.  
  191.  
  192. - (NSString *)name // getter
  193. {
  194. return name;
  195. }
  196.  
  197.  
  198. - (void)setName: (NSString *)newName // setter
  199. {
  200. name = newName;
  201. }
  202.  
  203. @end
  204.  
  205.  
  206. // accessing properties
  207. PropertiesExample *example = [PropertiesExample alloc];
  208.  
  209. // setter
  210. example.count = 10; // using the "dot-syntax"
  211. [example setCount:10]; // same thing, but calling the setter manually
  212. example.name = @"Name";
  213.  
  214. // getter
  215. int c = example.count; // using dot-syntax
  216. c = [example value]; // same thing, but calling getter manually
  217. NSString* n = example.name;
  218.  
  219.  
  220. //////////// Property attributes ///////////
  221.  
  222. @interface PropertyAttributeExample // example of using property attributes
  223. {
  224. int age;
  225. NSString* firstName;
  226. float bigness;
  227. }
  228.  
  229. @property (readonly) int age; // variable "age" cannot be modified, only getter will be created
  230. // getter for this one will be different
  231. @property (readwrite, copy, getter=sayMyName) NSString *firstName; // variable can be changed, but setter will copy object, not just assign pointer to existing one
  232. @property float size; // this instance variable doesn't exist, but it's ok
  233.  
  234. @end
  235.  
  236.  
  237.  
  238. @implementation PropertyAttributeExample
  239.  
  240. // use "bigness" to store size
  241. @synthesize size = bigness;
  242.  
  243. @dynamic firstName;
  244.  
  245.  
  246. // this is similar to what compiler does when "copy" attribute is set and setter is called
  247. - (void)setFirstName: (NSString *)newFirstName
  248. {
  249. if ( firstName != newFirstName )
  250. {
  251. [firstName release]; // kill old string
  252. firstName = [newFirstName copy]; // make a copy of "newFirstName" and assign it to firstName
  253. }
  254. }
  255.  
  256.  
  257. - (NSString *)sayMyName // this is THE getter, according to the @property declaration
  258. {
  259. return firstName;
  260. }
  261. @end
  262.  
  263.  
  264. //////////// Properties and dot-syntax ///////////
  265.  
  266. self.age = 10; // this will call "setAge" setter instead of accessing instance variable called "age"
  267. age = 10; // this will assign 10 to variable called "age" directly
  268.  
  269.  
  270. //////////// Key-Value coding ////////////
  271.  
  272. @interface KeyValueCodingExample // Key-Value Coding example
  273. {
  274. int age;
  275. }
  276.  
  277. @property int age;
  278.  
  279. - (void)main;
  280.  
  281. @end
  282.  
  283.  
  284. // implementation
  285. @implementation KeyValueCodingExample // Key-Value Coding example
  286.  
  287. @synthesize age;
  288.  
  289. - (void)main
  290. {
  291. // you can set "age" using a setter
  292. self.age = 10;
  293.  
  294. // or you can set "age" using KVC notation like this
  295. [self setValue:10 forKey:@"age"];
  296.  
  297. // you can retrieve "age" using a getter
  298. int a = self.age;
  299.  
  300. // or you can use KVC notation again
  301. a = [self valueForKey:@"age"];
  302. }
  303.  
  304. @end
  305.  
  306.  
  307. //////////// Declaring protocol ////////////
  308.  
  309. @protocol ProtocolExample // declaring a protocol called ProtocolExample
  310.  
  311. - (void)displayText: (NSString *)text; // by default, method is required
  312.  
  313. @optional
  314. - (void)singAndDance; // optional method
  315.  
  316. @required
  317. - (int)fetchCounter; // required method
  318.  
  319. @end
  320.  
  321.  
  322. // example of a class that adopts protocol
  323. @interface UsingProtocolExample : NSObject <ProtocolExample> // adopting a protocol
  324.  
  325. @end
  326.  
  327.  
  328. @implementation UsingProtocolExample // adopting a protocol
  329.  
  330. // we MUST implement this one, it came from the protocol
  331. - (void)displayText: (NSString *)text
  332. {
  333. }
  334.  
  335. // we MUST implement this one, it came from the protocol
  336. - (int)fetchCounter
  337. {
  338. }
  339.  
  340. @end
  341.  
  342.  
  343. @protocol ProtocolExample; // we are "importing" ProtocolExample
  344.  
  345. @protocol SubProtocolExample <ProtocolExample> // incorporating one protocol into another
  346.  
  347. @end
  348.  
  349.  
  350. //////////// Conformity to a protocol and type checking ////////////
  351.  
  352. if ( [object conformsToProtocol:@protocol(ProtocolExample)] ) {
  353. // yes, "object" implements all methods defined in ProtocolExample
  354. }
  355.  
  356.  
  357. id <ProtocolExample> anObjectProto; // object of any type that supports ProtocolExample protocol
  358.  
  359. Example <ProtocolExample> *obj; // object inherited from Example AND supports ProtocolExample protocol
  360.  
  361.  
  362. //////////// Selectors ////////////
  363.  
  364. // check whether object has method "displayText"
  365. if ( [object respondsTo:@selector(displayText:)] ) {
  366.  
  367. // invoke that method
  368. [object performSelector:@selector(displayText:) withObject:@"Hello world!"];
  369. // same as
  370. [object displayText:@"Hello world!"];
  371. }
  372.  
  373. // can also refer to selectors
  374. SEL request = @selector(displayText:);
  375. // same as
  376. SEL request = NSSelectorFromString(@"displayText:");
  377.  
  378. NSString *method = NSStringFromSelector(request); // this would be equal to "displayText:"
  379.  
  380. SEL currentMethod = _cmd; // tells us what method we are in right now
  381.  
  382.  
  383. //////////// Fast enumeration ////////////
  384.  
  385. NSArray *array = [NSArray arrayWithObjects:@"hello", @"world", nil]; // nil here means "end of array"
  386.  
  387. for (NSString *text in array) { // go through all strings in that array one by one
  388. // do something with "text"
  389. }
  390.  
  391. // if you wanna write class that can be enumerated, conform to NSFastEnumeration protocol
  392.  
  393.  
  394. //////////// Exception handling ////////////
  395.  
  396. @implementation ExceptionExample // Exception handling
  397. - (void)main
  398. {
  399. @try {
  400. // do something that might throw an exception
  401. NSException *ex = [NSException exceptionWithName:@"ConnectionLostException", reason:@"Network went down", userInfo:@"restart modem"];
  402.  
  403. @throw ex;
  404. }
  405. @catch( NSException *exception ) { // will catch any exception type inherited from NSException
  406. NSString *name = [exception name];
  407. NSString *reason = [exception reason];
  408. }
  409. @finally { // will get executed regardless whether exception thrown or not
  410.  
  411. }
  412. }
  413.  
  414. @end
  415.  
  416.  
  417. //////////// Threading and synchronization ////////////
  418.  
  419. @implementation SynchronizationExample
  420.  
  421. - (void)synchronize
  422. {
  423. @synchronized(self) {
  424. // will be synchronized on the instance
  425. }
  426.  
  427. @synchronized(NSStringFromSelector(_cmd)) {
  428. // will be synchronized on the name of the currently executing method
  429. }
  430. }
  431.  
  432. @end
  433.  
  434.  
  435. //////////// Logging ////////////
  436.  
  437. NSString *text = @"string variable";
  438. NSInteger i = 42;
  439.  
  440. // this will print out "Logging example: string variable, 42"
  441. NSLog(@"Logging example: %@, %@", text, i);
  442.  
  443. // %@ inside of the format string means "Objective-C object, printed as the string returned by 'descriptionWithLocale:' if available, or 'description' otherwise" - sort of like toString() in Java
  444.  
  445.  
  446.  
  447. //////////// Variable number of arguments ////////////
  448.  
  449. @interface VariableArgumentsExample
  450.  
  451. - (void)printStrings:(NSString *)string, ...; // this is how you define function with var number of args
  452.  
  453. @end
  454.  
  455.  
  456. @implementation VariableArgumentsExample
  457.  
  458. - (void)printStrings:(NSString *)string, ...
  459. {
  460. va_list ap;
  461. va_start(ap, string);
  462.  
  463. NSString* str = string;
  464.  
  465. while( str != null ) {
  466. NSLog( @"Got string: %@", str );
  467.  
  468. str = va_arg( ap, (NSString *));
  469. }
  470.  
  471. va_end( ap );
  472. }
  473.  
  474. @end
Add Comment
Please, Sign In to add comment