Objective-C basic learning notes

Source: Internet
Author: User

Objective-CThe basic notes for learning are described in this article,CocoaIt consists of two frameworks: Foundation Kit and Application Kit. The Application includes all user interface objects and advanced classes. The Foundation framework includes data-oriented low-level classes and data types with over 100 classes, suchNSString, NSArray, NSEnumerator, NSNumber, etc. The relevant documents are stored in/Developer/ADC Reference Library/documentation/index.html.

1. Common Data Types

 
 
  1. typedef struct _NSRange{  
  2. unsigned int location;  
  3. unsigned int length;  
  4. }NSRange; 

Indicates the range of coherent things. For example, the range of characters in a string may be the range of elements in an array. Location is the starting position of the range, and the number of length elements.

Creation measures:

 
 
  1. Nsange range; range. location = 1; range. length = 4;
  2. Nsange range = {}; // The aggregation structure Assignment Mechanism in C Language
  3. Nsange range = NSMakeRange (); // you can call NSMakeRange wherever you can use the function.
  4. Typedef struct _ NSPoint {
  5. Float x; float y;
  6. } NSPoint;
  7. Typedef struct _ NSSize {
  8. Float width; float height;
  9. } NSSize;
  10. Typedef struct _ NSRect {
  11. NSPoint origin; NSSize size;
  12. } NSRect;

NSRect is a rectangular data type, NSPoint is the starting point, NSSize storage length and width. NSMakeRect () NSMakePoint ().

These commonly used data types are C's struct rather than objects, and there are many temporary points, sizes, and rectangles in many processes, such as GUI processes, all Objective-C objects are dynamically allocated. This is a costly monopoly and requires a lot of effort.

2. String

CocoaThe NSString class that processes the string and its subclass NSMutableString.

 
 
  1. +(id)stringWithFormat:(NSString *)format,...; 

Multiple parameters that can be separated by commas. + This is a class action and belongs to the class object. When Obj-C produces a class, it creates a class object that represents the class, including a pointer to the super class, a class name and a pointer to the class measure list. It also includes a long data nanjianyan.com, which specifies the size of the newly created class instance object. -To start declaring instance actions. These instance actions may run in an object instance. If a measure is used to end a conventional function, such as creating an instance object, it may call some of the big picture data and declare it as a class measure.

-(Unsigned int) length; it can accurately process international strings. Chinese, Japanese, and strings that use Unicode international character standards. Processing these international strings in C is cumbersome, because a character can be used to store more than one byte, and strlen () can only calculate the number of bytes.

-(BOOL) isEqualtoString :( NSString *) str; and = the operator can only deduce the two string pointer values, but never deduce the objects they direct.

 
 
  1. -(NSComparisonResult)compare:(NSString *)str options:(unsigned)mask; 

NSComparisonResult is an enum-type data.

 
 
  1. typedef enum _NSComparisonResult{  
  2. NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending  
  3. }NSComparisonResult; 

Options is a bit mask, which can use a bit or | to add an option symbol. NSCaseInsensitiveSearch is case-insensitive, and NSLiteralSearch is case-insensitive. NSNumericSearch is more case-insensitive than string characters.

 
 
  1. NSString *str1 = @"hello 1 world";  
  2. NSString *str2;  
  3. str2 = [NSString stringWithFormat:@"hello %d world",1];  
  4. if([str1 compare:str2  
  5. options:NSCaseInsensitiveSearch | NSNumericSearch]  
  6. == NSOrderedSame)  
  7. {} 

Once NSString is created, it cannot be changed. It can be used to generate new strings, which may be comparable to search characters. However, you cannot remove the characters that may be added. The variable NSMutableString is a subclass of NSString. They are in a. h file.

 
 
  1. +(id)stringWithCapacity:(unsigned)capacity; 

Creates a capacity string. Pre-allocate a piece of memory to store it, and the subsequent monopoly will be much faster. Of course, it can also be used by both the class and instance measures of its parent class NSString.

 
 
  1. NSMutableString * friends;
  2.  
  3. Friends = [NSMutalbeString stringWithCapacity: 50];
  4. [Friends appendString: @ "James lilei lucy"]; // Add a string to the end of the object
  5.  
  6. Nsange range;
  7. Range = [friends rangeOfString: @ "lilei"]; // query the range of str2 in str1
  8.  
  9. Range. length ++;
  10. [Friends deleteCharactersInRange :( nsange) range]; // remove characters from the traversal range

3. Aggregation

 
 
  1. NSArray,NSMutalbeArray,NSEnumerator,NSDictionary 

The NSArray class is an ordered list of stored objects. Only the Objective-C object is stored, and the approximate data types int, float, enum, and struct in C are not stored. May be the pointer in NSArray. At the same time, the nil object's zero value may be NULL ).

NSArray * array = [NSArray arrayWithObjects: @ "1", @ "2", @ "three", nil]; do1k.com ends with nil. This is one of the reasons for not storing nil.

 
 
  1. for(int i=0;i<[array count];i++){NSLog(@"index %d has %@", i, [array objectAtIndex:i]);} 

-(Unsigned) count, including the number of objects. -(Id) objectAtIndex :( unsigned int) index; get the object at a specific index.

Abnormal handling:

In case that the index is greater than the number of array objects: Terminating app due to uncaught exception 'nsangeexception' reason: '...', there are a large number of catch exceptions and processing duplicates.

CF: the Core Foundatin framework is used in the same way as the Cocoa framework, but it ends in the C language. The objects in CF and Cocoa objects are directly Bridging for free and can be used interchangeably.

Split array:

Perl may be used in Python to split strings into arrays and combine array elements into strings. NSArray can also!

 
 
  1. NSString *str = @"opp:abc:book:come";  
  2. NSString *chunks = [str componentsSeparatedByString:@":"];  
  3. str = [chunks componentsJoinedByString:@":)"]; 

Str at this time is "opp :) abc :) book :) come"

 
 
  1. NSMutalbeArray:
  2. + (IdarrayWithCapacity :( unsigned) numltems; // pre-allocates a size, and does not pre-Write the object into an array or limit the array size.
  3. -(Void) addObject :( id) anObject; // Add an object at the end of the array
  4. -(Void) removeObjectAtIndex :( unsigned) index; // removes an object. important indexes start from 0 and are removed from the array element behind the object to add vacancies.
  5. NSEnumerator enumeration to facilitate Arrays
  6. -(NSEnumerator *) objectEnumerator; // request the enumerator from the array
  7. -(Id) nextObject; // request the next object from the enumerator. Returning nil indicates the end of the pleading
  8. NSEnumerator * enumerator;
  9. Id thingid;
  10. Enumerator = [array objectEnumerator];
  11. While (thingid = [enumerator nextObject]) {}

Enumeration quickly. In Objective-C 2.0, quick enumeration is performed.

 
 
  1. For (NSString * str in array) {NSLog (@ "% @", str);} 62.syxinhao.com//cyclic experience facilitates each element in the array

NSDictionary stores a value object under a given keyword such as a string), and then can search for the corresponding value through the keyword.

 
 
  1. Tire * t1 = [Tire new];... Tire * t4 = [Tire new];
  2. NSDictionary * tires = [NSDictionary dictionaryWithObjectsAndKeys: t1, @ "f_l", t2, @ "f_r", t3, @ "B _l", t4, @ "B _r", nil];
  3. // Accept objects and keywords are stored alternately. Nil termination
  4. Tire * tire = [tires objectForKey: @ "l_r"];
  5. // Return an id. Here it is a Tire object. If the l_r keyword is not returned, nil is returned.

NSMutableDictionary and NSMutableArray have similar monopoly.

It is not easy to create a subclass of NSString, NSArray, and NSDictionary! Many classes end with cluster-based measures. They are a group of classes that are hidden in the universal interface. When creating an NSString object, you may obtain NSLiteralString, NSCFString, and NSSimpleCString objects. Creating subclasses for class clusters is cumbersome. However, the ability to compose NSString to a class of our own may be handled by vielai, without the need to create subclasses.

4. Numeric Value

NSArray and NSDictionary cannot store any type of data. We can use an object to encapsulate approximate values and then include the object into NSArray.

 
 
  1. NSNumber:
  2. NSNumber * num;
  3. Num = [NSNumber numberWithInt/Char/Float/Bool: 1];
  4. [Array addObject: num];
  5. [Dictionary setObject: num forKey: @ "book"];
  6. -(Char) charValue;-(int) intValue;...-(NSString *) stringValue; used to parse data encapsulated in NSNumber.
  7. NSValue:

NSNumber is a subclass of NSValue. NSValue can wrap any value. Can be used for packaging and construction.

 
 
  1. NSRect rect = NSMakeRect(1,1,20,20);  
  2. NSValue *value;  
  3. value = [NSValue valueWithBytes:&rect  
  4. objCType:@encode(NSRect)]; 

// (Const void *) Address of the variable to be stored by value. C &. @ Encode the compiler can accept the data type name and generate a lightweight string.

 
 
  1. [array addObject:value]; 

Extraction:

 
 
  1. Value = [array objectAtIndex: 0];
  2. [Value getValue: & rect]; // get

(Void *) the space pointed to by the value pointer to store the data generated by this measure.

For construction:

 
 
  1. +(NSValue *)valueWithRect:(NSRect)rect; -(NSRect) rectValue;  
  2. NSNULL: 

Only one action + (NSNull *) null;

In NSArray, it may be indicated that nothing exists here in NSDictionary. Because nil is used.

 
 
  1. [contact setObject:[NSNull null]  
  2. forKey:@"haha"];  
  3. id hahaid;  
  4. hahaid = [contact objectForKey:@"haha"];  
  5. if(hahaid == [NSNull null]) {} //[NSNull null] 

The return value is always the same, so we can use = to compare the return value. Code Review-errors detected by comrades looking for errors in code-are different from errors observed during tests.

Summary:Objective-CI hope this article will help you with the introduction of basic notes!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.