逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::
Adopted Protocols
NSCoding例子
- (id)initWithCoder:(NSCoder *)coder {
    if (self = [super init]) {
        [self setName:[coder decodeObject]];
        [self setPrice:[coder decodeObject]];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:name]; // 注意与decodeObject的顺序一致
    [coder encodeObject:price];
}

arrayWithArray:

Creates and returns an array containing the objects in another given array.

+ (id)arrayWithArray:(NSArray *)anArray
Parameters
anArray

An array.

Return Value

An array containing the objects in anArray.


arrayWithContentsOfFile:

Creates and returns an array containing the contents of the file specified by a given path.

+ (id)arrayWithContentsOfFile:(NSString *)aPath
Parameters
aPath

The path to a file containing a string representation of an array produced by the writeToFile:atomically: method.

Return Value

An array containing the contents of the file specified by aPath. Returns nil if the file can’t be opened or if the contents of the file can’t be parsed into an array.

Discussion

The array representation in the file identified by aPath must contain only property list objects (NSStringNSDataNSDateNSNumberNSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this array are immutable, even if the array is mutable.

arrayWithContentsOfURL:

arrayWithObjects:

Creates and returns an array containing the objects in the argument list.

+ (id)arrayWithObjects:(id)firstObj, ...
Parameters
firstObj, ...

A comma-separated list of objects ending with nil. // 要以nil结尾

Return Value

An array containing the objects in the argument list.

Discussion

This code example creates an array containing three different types of element:

NSArray *myArray;
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = @"a string";
 
myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];

arrayWithObjects:count:

Creates and returns an array that includes a given number of objects from a given C array.

+ (id)arrayWithObjects:(const id *)objects count:(NSUInteger)count
Parameters
objects

A C array of objects.

count

The number of values from the objects C array to include in the new array. This number will be the count of the new array—it must not be negative or greater than the number of elements in objects.

Return Value

A new array including the first count objects from objects.

Discussion

Elements are added to the new array in the same order they appear in objects, up to but not including index count. For example:

NSString *strings[3];
strings[0] = @"First";
strings[1] = @"Second";
strings[2] = @"Third";
 
NSArray *stringsArray = [NSArray arrayWithObjects:strings count:2];
// strings array contains { @"First", @"Second" }

arrayByAddingObject:

Returns a new array that is a copy of the receiving array with a given object added to the end.

- (NSArray *)arrayByAddingObject:(id)anObject
Parameters
anObject

An object.

Return Value

A new array that is a copy of the receiving array with anObject added to the end.

Discussion

If anObject is nil, an NSInvalidArgumentException is raised.


arrayByAddingObjectsFromArray:

Returns a new array that is a copy of the receiving array with the objects contained in another array added to the end.

- (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray
Parameters
otherArray

An array.

Return Value

A new array that is a copy of the receiving array with the objects contained in otherArray added to the end.

See Also


componentsJoinedByString:

Constructs and returns an NSString object that is the result of interposing a given separator between the elements of the array.

- (NSString *)componentsJoinedByString:(NSString *)separator
Parameters
separator

The string to interpose between the elements of the array.

Return Value

An NSString object that is the result of interposing separator between the elements of the array. If the array has no elements, returns an NSString object representing an empty string.

Discussion

For example, this code excerpt writes "here be dragons" to the console:

NSArray *pathArray = [NSArray arrayWithObjects:@"here", @"be", @"dragons", nil];
NSLog(@"%@",[pathArray componentsJoinedByString:@" "]);
Special Considerations

Each element in the array must handle description.


containsObject:

Returns a Boolean value that indicates whether a given object is present in the array.

- (BOOL)containsObject:(id)anObject
Parameters
anObject

An object.

Return Value

YES if anObject is present in the array, otherwise NO.

Discussion

This method determines whether anObject is present in the array by sending an isEqual: message to each of the array’s objects (and passing anObject as the parameter to eachisEqual: message).


count

Returns the number of objects currently in the array.

- (NSUInteger)count
Return Value

The number of objects currently in the array. nil不计算在内


NSEnumerationOptions

Options for Block enumeration operations.

enum {   NSEnumerationConcurrent = (1UL << 0),   NSEnumerationReverse = (1UL << 1),};typedef NSUInteger NSEnumerationOptions;
Constants
NSEnumerationConcurrent

Specifies that the Block enumeration should be concurrent.

The order of invocation is nondeterministic and undefined; this flag is a hint and may be ignored by the implementation under some circumstances; the code of the Block must be safe against concurrent invocation.

Available in Mac OS X v10.6 and later.

Declared in NSObjCRuntime.h.

NSEnumerationReverse

Specifies that the enumeration should be performed in reverse.

This option is available for NSArray and NSIndexSet classes; its behavior is undefined for NSDictionary and NSSet classes, or when combined with theNSEnumerationConcurrent flag.

Available in Mac OS X v10.6 and later.

Declared in NSObjCRuntime.h.

Declared In
NSObjCRuntime.h

enumerateObjectsWithOptions:usingBlock:

Executes a given block using each object in the array.

- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
Parameters
opts

A bitmask that specifies the options for the enumeration (whether it should be performed concurrently and whether it should be performed in reverse order).

block

The block to apply to elements in the array.

The block takes three arguments:

obj

The element in the array.

idx

The index of the element in the array.

stop

A reference to a Boolean value. The block can set the value to YES to stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

Discussion

By default, the enumeration starts with the first object and continues serially through the array to the last object. You can specify NSEnumerationConcurrent and/orNSEnumerationReverse as enumeration options to modify this behavior.

Important: If the Block parameter is nil this method will raise an exception.


filteredArrayUsingPredicate:

Evaluates a given predicate against each object in the receiving array and returns a new array containing the objects for which the predicate returns true.

- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate
Parameters
predicate

The predicate against which to evaluate the receiving array’s elements.

Return Value

A new array containing the objects in the receiving array for which predicate returns true.


getObjects:range:

Copies the objects contained in the array that fall within the specified range to aBuffer.

- (void)getObjects:(id *)aBuffer range:(NSRange)aRange
Parameters
aBuffer

A C array of objects of size at least the length of the range specified by aRange.

aRange

A range within the bounds of the array.

If the location plus the length of the range is greater than the count of the array, this method raises an NSRangeException.

Discussion

The method copies into aBuffer the objects in the array in the range specified by aRange; the size of the buffer must therefore be at least the length of the range multiplied by the size of an object reference, as shown in the following example (this is solely for illustration—you should typically not create a buffer simply to iterate over the contents of an array):

NSArray *mArray = // an array with at least six elements...;
id *objects;
 
NSRange range = NSMakeRange(2, 4);
objects = malloc(sizeof(id) * range.length);
 
[mArray getObjects:objects range:range];
 
for (i = 0; i < range.length; i++) {
    NSLog(@"objects: %@", objects[i]);
}
free(objects);

indexOfObject:

Returns the lowest index whose corresponding array value is equal to a given object.

- (NSUInteger)indexOfObject:(id)anObject
Parameters
anObject

An object.

Return Value

The lowest index whose corresponding array value is equal to anObject. If none of the objects in the array is equal to anObject, returns NSNotFound.

Discussion

Starting at index 0, each element of the array is sent an isEqual: message until a match is found or the end of the array is reached. This method passes the anObject parameter to each isEqual: message. Objects are considered equal if isEqual: (declared in the NSObject protocol) returns YES.

NSNotFound

Defines a value that indicates that an item requested couldn’t be found or doesn’t exist.

enum {   NSNotFound = NSIntegerMax};
Constants
NSNotFound

A value that indicates that an item requested couldn’t be found or doesn’t exist.

Available in Mac OS X v10.0 and later.

Declared in NSObjCRuntime.h.

Discussion

NSNotFound is typically used by various methods and functions that search for items in serial data and return indices, such as characters in a string object or ids in an NSArrayobject.

Special Considerations

Prior to Mac OS X v10.5, NSNotFound was defined as 0x7fffffff. For 32-bit systems, this was effectively the same as NSIntegerMax. To support 64-bit environments,NSNotFound is now formally defined as NSIntegerMax. This means, however, that the value is different in 32-bit and 64-bit environments. You should therefore not save the value directly in files or archives. Moreover, sending the value between 32-bit and 64-bit processes via Distributed Objects will not get you NSNotFound on the other side. This applies to any Cocoa methods invoked over Distributed Objects and which might return NSNotFound, such as the indexOfObject: method of NSArray (if sent to a proxy for an array).

NSRange

A structure used to describe a portion of a series—such as characters in a string or objects in an NSArray object.

typedef struct _NSRange {      NSUInteger location;      NSUInteger length;} NSRange;
Fields
location

The start index (0 is the first, as in C arrays).

length

The number of items in the range (can be 0).

makeObjectsPerformSelector:

Sends to each object in the array the message identified by a given selector, starting with the first object and continuing through the array to the last object.

- (void)makeObjectsPerformSelector:(SEL)aSelector
Parameters
aSelector

A selector that identifies the message to send to the objects in the array. The method must not take any arguments, and must not have the side effect of modifying the receiving array.


objectAtIndex:

Returns the object located at index.

- (id)objectAtIndex:(NSUInteger)index
Parameters
index

An index within the bounds of the array.

Return Value

The object located at index.

Discussion

If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

objectEnumerator

Returns an enumerator object that lets you access each object in the array.

- (NSEnumerator *)objectEnumerator
Return Value

An enumerator object that lets you access each object in the array, in order, from the element at the lowest index upwards.

Discussion

Returns an enumerator object that lets you access each object in the array, in order, starting with the element at index 0, as in:

NSEnumerator *enumerator = [myArray objectEnumerator];
id anObject;
 
while (anObject = [enumerator nextObject]) {
    /* code to act on each element as it is returned */
}
Special Considerations

When you use this method with mutable subclasses of NSArray, you must not modify the array during enumeration.

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on Mac OS X v10.5 and later and iOS 2.0 and later.

pathsMatchingExtensions:

Returns an array containing all the pathname elements in the receiving array that have filename extensions from a given array.

- (NSArray *)pathsMatchingExtensions:(NSArray *)filterTypes
Parameters
filterTypes

An array of NSString objects containing filename extensions. The extensions should not include the dot (“.”) character.

Return Value

An array containing all the pathname elements in the receiving array that have filename extensions from the filterTypes array.

setValue:forKey:

Invokes setValue:forKey: on each of the array's items using the specified value and key.

- (void)setValue:(id)value forKey:(NSString *)key
Parameters
value

The object value.

key

The key to store the value.

sortedArrayUsingComparator:

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator Block.

- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
Parameters
cmptr

A comparator block.

Return Value

An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified cmptr.

NSComparator

Defines the signature for a block object used for comparison operations.

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
Discussion

The arguments to the block are two objects to compare. The block returns an NSComparisonResult value to denote the ordering of the two objects.

You use NSComparator blocks in comparison operations such as NSArray’s sortedArrayUsingComparator:, for example:

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
 
    if ([obj1 integerValue] > [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
 
    if ([obj1 integerValue] < [obj2 integerValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

NSComparisonResult

These constants are used to indicate how items in a request are ordered.

enum {   NSOrderedAscending = -1,   NSOrderedSame,   NSOrderedDescending};typedef NSInteger NSComparisonResult;
Constants
NSOrderedAscending

The left operand is smaller than the right operand.

Available in Mac OS X v10.0 and later.

Declared in NSObjCRuntime.h.

NSOrderedSame

The two operands are equal.

Available in Mac OS X v10.0 and later.

Declared in NSObjCRuntime.h.

NSOrderedDescending

The left operand is greater than the right operand.

Available in Mac OS X v10.0 and later.

Declared in NSObjCRuntime.h.

sortedArrayUsingSelector:

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given selector.

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator
Parameters
comparator

A selector that identifies the method to use to compare two elements at a time. The method should return NSOrderedAscending if the receiving array is smaller than the argument, NSOrderedDescending if the receiving array is larger than the argument, and NSOrderedSame if they are equal.

Return Value

An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by the selector comparator.

Discussion

The new array contains references to the receiving array’s elements, not copies of them.

The comparator message is sent to each object in the array and has as its single argument another object in the array.

For example, an array of NSString objects can be sorted by using the caseInsensitiveCompare: method declared in the NSString class. Assuming anArray exists, a sorted version of the array can be created in this way:

     NSArray *sortedArray =
         [anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

subarrayWithRange:

Returns a new array containing the receiving array’s elements that fall within the limits specified by a given range.

- (NSArray *)subarrayWithRange:(NSRange)range
Parameters
range

A range within the receiving array’s range of elements.

Return Value

A new array containing the receiving array’s elements that fall within the limits specified by range.

Discussion

If range isn’t within the receiving array’s range of elements, an NSRangeException is raised.

For example, the following code example creates an array containing the elements found in the first half of wholeArray (assuming wholeArray exists).

NSArray *halfArray;
NSRange theRange;
 
theRange.location = 0;
theRange.length = [wholeArray count] / 2;
 
halfArray = [wholeArray subarrayWithRange:theRange];

subarrayWithRange:

Returns a new array containing the receiving array’s elements that fall within the limits specified by a given range.

- (NSArray *)subarrayWithRange:(NSRange)range
Parameters
range

A range within the receiving array’s range of elements.

Return Value

A new array containing the receiving array’s elements that fall within the limits specified by range.

Discussion

If range isn’t within the receiving array’s range of elements, an NSRangeException is raised.

For example, the following code example creates an array containing the elements found in the first half of wholeArray (assuming wholeArray exists).

NSArray *halfArray;
NSRange theRange;
 
theRange.location = 0;
theRange.length = [wholeArray count] / 2;
 
halfArray = [wholeArray subarrayWithRange:theRange];

writeToFile:atomically:

Writes the contents of the array to a file at a given path.

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
Parameters
path

The path at which to write the contents of the array.

If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

flag

If YES, the array is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the array is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

Return Value

YES if the file is written successfully, otherwise NO.

Discussion

If the array’s contents are all property list objects (NSStringNSDataNSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: or the instance method initWithContentsOfFile:. This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

@import url(http://www.cppblog.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
posted on 2011-12-02 00:13 逛奔的蜗牛 阅读(1414) 评论(0)  编辑 收藏 引用 所属分类: Cocoa

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理