Objective, objectivec

Source: Internet
Author: User

Objective, objectivec

Objective-c Foundation framework details 2

 

Collection Agency

Cocoa provides a number of collection classes such as NSArray and NSDictionary whose instances exist just to hold onto other objects.

Cocoa provides a series of collection classes, such as NSarray and NSdictionary. They exist to keep other objects.

1.1.1NSArray is a Cocoa class that holds an ordered list of objects. you can put any kind of objects in an NSArray: NSString, Car, Shape, Tire, or whatever else you want, even other arrays and dictionaries.

NSArray is a cocoa class that provides an ordered list of objects. You can enter any object.

 

NSArray has two limitations. first, it holds only Objective-C objects. you can't have primitive C types, like int, float, enum, struct, or random pointers in an NSArray. also, you can't store nil (the zero or NULL value for objects) in an NSArray.

NSarray has two limits. First, only objective-c objects can be stored, and C language objects, such as float, cannot be stored. Second, Nil cannot be stored.

 

You can create a new NSArray using the class method arrayWithObjects :. you give it a comma-separated list of objects, with nil at the end to signal the end of the list (which, by the way, is one of the reasons you can't store nil in an array ):

Arraywithobject must end with nil.

NSArray * array = [NSArray arrayWithObjects: @ "one", @ "two", @ "three", nil];

1.1.2Once you have an array, you can get a count of the number of objects it contains:

-(NSUInteger) count;

And you can fetch an object at a participant index:

-(Id) objectAtIndex :( NSUInteger) index;

 

For (NSInteger I = 0; I <[array count]; I ++)

{

NSLog (@ "index % d has % @.", I, [array objectAtIndex: I]);

}

You can also write the preceding code using the array literal syntax:

For (NSInteger I = 0; I <[array count]; I ++)

{

NSLog (@ "index % d has % @.", I, array [I]);

}

1.1.3 Mutable arrays

It uses a class method, arrayWithCapacity, to make a new mutable array:

+ (Id) arrayWithCapacity: (NSUInteger) numItems;

NSMutableArray * array = [NSMutableArray arrayWithCapacity: 17];

Add objects to the end of the array by using addObject :.
-(Void) addObject: (id) anObject;

You can add four tires to an array with a loop like this:

 

For (NSInteger I = 0; I <4; I ++)

{

Tire * tire = [Tire new];

[Array addObject: tire];

}

You can remove an object at a participant index. for example, if you don't like the second tire, you can use removeObjectAtIndex: to get rid of it. here's how the method is defined:

-(Void) removeObjectAtIndex: (NSUInteger) index;

You use it like this:

[Array removeObjectAtIndex: 1];

 

1.2.1Enumeration Nation Enumeration

NSEnumerator, which is Cocoa's way of describing this kind of iteration over a collection.

Enumeration, cocoa method, describes the iteration of a container.

Use NSEnumerator, you ask the array for the enumerator using objectEnumerator:

-(NSEnumerator *) objectEnumerator;

You use the method like this: for example:

NSEnumerator * enumerator = [array objectEnumerator];

After you get an enumerator, you crank up a while loop that asks the enumerator for its

NextObject every time through the loop:

-(Id) nextObject;

When nextObject returns nil, the loop is done.

If nextObject returns nil, the loop ends.

NSEnumerator * enumerator = [array objectEnumerator];

While (id thingie = [enumerator nextObject])

{

NSLog (@ "I found % @", thingie );

}

 

There's one gotcha if you're enumerating over a mutable array: you can't change the container

If you are operating on a variable array, do not change the container during traversal.

 

1.2.2 Fast Enumeration

For (NSString * string in array)

{

NSLog (@ "I found % @", string );

}

 

To support the blocks feature, Apple has added a method to enumerate objects in NSArray using blocks, and it looks like this.

To support block, Apple added a method to support block for series.

-(Void) enumerateObjectsUsingBlock :( void (^) (id obj, NSUInteger idx, BOOL * stop) block

[Array enumerateObjectsUsingBlock: ^ (NSString * string, NSUInteger index, BOOL * stop ){

NSLog (@ "I found % @", string );

}];

 

Now, the question is, "Why wocould we use this instead of fast enumeration? "With blocks, one of the options is that the loop can execute in parallel. With fast enumeration, execution proceeds through the items linearly.

This is intended for concurrent execution.

 

1.3 NSDictionary dictionary

An NSDictionary stores a value (which can be any kind of Objective-C object) under a given key (usually an NSString ).

Dictionary stores any value under a given keyword (generally NSString)

However, the NSMutableDictionary class lets you add and remove stuff at will.

NSMutableDictionary allows you to add and delete data freely.

The easiest way to get started with a dictionary is to use the dictionary literal syntax, which is similar to the class method dictionaryWithObjectsAndKeys :.

It is easiest to construct a dictionary word by word:

The literal syntax is defined as @ {key: value ,...};

The literal value is key: value.

NSDictionary * tires = [NSDictionary dictionaryWithObjectsAndKeys: t1,

@ "Front-left", t2, @ "front-right", t3, @ "back-left", t4, @ "back-right", nil];

Or

NSDictionary * tires =@ {@ "front-left": ti, @ "front-right": t2, @ "back-left": t3,

@ "Back-right": t4 };

 

To access a value in the dictionary, use the objectForKey: method, giving it the key you previusly stored the value under:

Get a value dictionary:

-(Id) objectForKey: (id) aKey;

Or

Tires [key];

 

To make a new NSMutableDictionary, send the dictionary message to the NSMutableDictionary class.

 

+ (Id) dictionaryWithCapacity: (NSUInteger) numItems;

You can add things to the dictionary using setObject: forKey :.

SetObject: forKey

-(Void) setObject :( id) anObject forKey :( id) aKey

NSMutableDictionary * tires = [NSMutableDictionary dictionary];

[Tires setObject: tl forKey: @ "front-left"];

[Tires setObject: t2 forKey: @ "front-right"];

[Tires setObject: t3 forKey: @ "back-left"];

[Tires setObject: t4 forKey: @ "back-right"];

If you want to take a key out of a mutable dictionary, use the removeObjectForKey:

Delete data:

Method:-(void) removeObjectForKey: (id) aKey;

[Tires removeObjectForKey: @ "back-left"];

 

1.4 NSNumber number

Cocoa provides a class called NSNumber that wraps (that is, implements as objects) the primitive numeric types.

NSNumber encapsulates native data types.

You can create a new NSNumber using these class methods:

+ (NSNumber *) numberWithChar: (char) value;

+ (NSNumber *) numberWithInt: (int) value;

+ (NSNumber *) numberWithFloat: (float) value;

+ (NSNumber *) numberWithBool: (BOOL) value;

 

You can also use the literal syntax to create these objects:

You can also create an object by word.

NSNumber * number;

Number = @ 'X'; // char

Number = @ 12345; // integer

Number = @ 12345ul; // unsigned long

Number = @ 12345ll; // long

Number = @ 123.45f; // float

Number = @ 123.45; // double

Number = @ YES; // BOOL

 

After you create an NSNumber, you can put it into a dictionary or an array:

In this way, you can put it into array or dictionary.

NSNumber * number = @ 42;

[Array addObject number];

[Dictionary setObject: number forKey: @ "Bork"];

 

Once you have a primitive type wrapped in an NSNumber, you can get it back out using one of these instance methods:

Once you have obtained an NSNumber for native data packaging, you can restore it below:

-(Char) charValue;

-(Int) intValue;

-(Float) floatValue;

-(BOOL) boolValue;

-(NSString *) stringValue;

 

1.5 NSValue Value

NSNumber is actually a subclass of NSValue, which wraps arbitrary values. You can use NSValue to put structures into NSArrays and NSDictionary objects.

NSValue is the base class of NSNumber. NSValue can store arbitrary values.

Create a new NSValue using this class method:

+ (NSValue *) valueWithBytes: (const void *) value objCType: (const char *) type;

 

You pass the address of the value you want to wrap (such as an NSSize or your own struct ). usually, you take the address (using the & operator in C) of the variable you want to save.

You may pass a worthwhile address.

So, to put an NSRect into an NSArray, you do something like this:

If you want to put an NSRect in NSArray,

NSRect rect = NSMakeRect (1, 2, 30, 40 );

NSValue * value = [NSValue valueWithBytes: & rect objCType: @ encode (NSRect)];

[Array addObject: value];

You can extract the value using getValue:
-(Void) getValue :( void *) buffer;

You can extract the value using getValue:
-(Void) getValue :( void *) buffer;
When you call getValue:, you pass the address of a variable that you want to hold the value:

When you call getValue, you can pass the address to value.

Value = [array objectAtIndex: 0];

[Value getValue: & rect];

 

Convenience methods are provided for putting common Cocoa structs into NSValues, and we have conveniently listed them here:

For convenience, list the following common classes:

+ (NSValue *) valueWithPoint :( NSPoint) aPoint;

+ (NSValue *) valueWithSize :( NSSize) size;

+ (NSValue *) valueWithRect :( NSRect) rect;

-(NSPoint) pointValue;

-(NSSize) sizeValue;

-(NSRect) rectValue;

To store and retrieve an NSRect in an NSArray, you do this:

Store or obtain NSrect in NSarray:

Value = [NSValue valueWithRect: rect];

[Array addObject: value];

...

NSRect anotherRect = [value rectValue];

 

1.6 NSNull null

We 've told you that you can't put nil into a collection, because nil has special meaning to NSArray and NSDictionary. but sometimes, you really need to store a value that means "there's nothing here at all."

We cannot store nil in containers because nil has special significance. But sometimes we do need to do this.

NSNull is probably the simplest of all Cocoa classes. It has but a single method:

NSNull is simple. There is a separate class method.

+ (NSNull *) null;

[Contact setObject: [NSNull null]

ForKey: @ "home fax machine"];

Id homefax = [contact objectForKey: @ "home fax machine"];

If (homefax = [NSNull null])

{

//... No fax machine. rats.

}

 

 

 

 

 

 

 

 

 

 

 

 

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.