Top Banner
Foundation Framework Reference Core Services Layer: Foundation 2008-06-27
1453
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Foundation Framework ReferenceCore Services Layer: Foundation

2008-06-27

Apple Inc. 1997, 2008 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Apples copyright notice. The Apple logo is a trademark of Apple Inc. Use of the keyboard Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of Apple may constitute trademark infringement and unfair competition in violation of federal and state laws. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-labeled computers. Every effort has been made to ensure that the information in this document is accurate. Apple is not responsible for typographical errors. Apple Inc. 1 Infinite Loop Cupertino, CA 95014 408-996-1010 Apple, the Apple logo, Bonjour, Carbon, Cocoa, eMac, Keychain, Mac, Mac OS, Macintosh, Objective-C, Pages, Quartz, Safari, and Xcode are trademarks of Apple Inc., registered in the United States and other countries. Finder, iPhone, and Numbers are trademarks of Apple Inc. Adobe, Acrobat, and PostScript are trademarks or registered trademarks of Adobe Systems Incorporated in the U.S. and/or other countries. Intel and Intel Core are registered trademarks of Intel Corportation or its subsidiaries in the United States and other countries.

Java and all Java-based trademarks are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. PowerPC and and the PowerPC logo are trademarks of International Business Machines Corporation, used under license therefrom. UNIX is a registered trademark of The Open Group Simultaneously published in the United States and Canada.Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.

ContentsIntroduction

The Foundation Framework 23Introduction 24

Part I Chapter 1

Classes 29 NSArray Class Reference 31Overview 31 Adopted Protocols 33 Tasks 34 Class Methods 37 Instance Methods 41

Chapter 2

NSAssertionHandler Class Reference 67Overview 67 Tasks 67 Class Methods 68 Instance Methods 68

Chapter 3

NSAutoreleasePool Class Reference 71Overview 71 Tasks 72 Class Methods 73 Instance Methods 74

Chapter 4

NSBundle Class Reference 77Overview 77 Tasks 78 Class Methods 81 Instance Methods 86 Constants 104 Notifications 105

Chapter 5

NSCachedURLResponse Class Reference 107Overview 107 Tasks 107 Instance Methods 108

32008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Constants 110 Chapter 6

NSCalendar Class Reference 113Overview 113 Tasks 114 Class Methods 115 Instance Methods 116 Constants 127

Chapter 7

NSCharacterSet Class Reference 131Overview 131 Adopted Protocols 132 Tasks 132 Class Methods 134 Instance Methods 142 Constants 145

Chapter 8

NSCoder Class Reference 147Overview 147 Tasks 148 Instance Methods 150

Chapter 9

NSCondition Class Reference 169Overview 169 Tasks 170 Instance Methods 171

Chapter 10

NSConditionLock Class Reference 175Overview 175 Adopted Protocols 175 Tasks 175 Instance Methods 176

Chapter 11

NSCountedSet Class Reference 181Overview 181 Tasks 182 Instance Methods 182

42008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 12

NSData Class Reference 187Overview 187 Adopted Protocols 188 Tasks 188 Class Methods 190 Instance Methods 195 Constants 205

Chapter 13

NSDate Class Reference 207Overview 207 Adopted Protocols 209 Tasks 209 Class Methods 210 Instance Methods 214 Constants 221

Chapter 14

NSDateComponents Class Reference 223Overview 223 Tasks 224 Instance Methods 225 Constants 234

Chapter 15

NSDateFormatter Class Reference 235Overview 235 Tasks 236 Class Methods 240 Instance Methods 241 Constants 270

Chapter 16

NSDecimalNumber Class Reference 273Overview 273 Tasks 273 Class Methods 276 Instance Methods 281 Constants 290

Chapter 17

NSDecimalNumberHandler Class Reference 291Overview 291 Adopted Protocols 291 Tasks 292

52008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Class Methods 292 Instance Methods 293 Chapter 18

NSDictionary Class Reference 295Overview 295 Adopted Protocols 297 Tasks 297 Class Methods 300 Instance Methods 306

Chapter 19

NSDirectoryEnumerator Class Reference 327Overview 327 Tasks 327 Instance Methods 328

Chapter 20

NSDistributedNotificationCenter Class Reference 331Class at a Glance 331 Overview 332 Constants 332

Chapter 21

NSEnumerator Class Reference 335Overview 335 Tasks 336 Instance Methods 336

Chapter 22

NSError Class Reference 339Overview 339 Adopted Protocols 340 Tasks 340 Class Methods 341 Instance Methods 341 Constants 346

Chapter 23

NSException Class Reference 349Overview 349 Adopted Protocols 349 Tasks 350 Class Methods 350 Instance Methods 352 Constants 355

62008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 24

NSFileHandle Class Reference 357Overview 357 Tasks 357 Class Methods 359 Instance Methods 363 Constants 373 Notifications 374

Chapter 25

NSFileManager Class Reference 377Overview 377 Tasks 377 Class Methods 382 Instance Methods 382 Delegate Methods 407 Constants 414

Chapter 26

NSFormatter Class Reference 421Overview 421 Tasks 421 Instance Methods 422

Chapter 27

NSHTTPCookie Class Reference 429Overview 429 Adopted Protocols 429 Tasks 430 Class Methods 431 Instance Methods 432 Constants 438

Chapter 28

NSHTTPCookieStorage Class Reference 441Overview 441 Tasks 441 Class Methods 442 Instance Methods 442 Constants 445 Notifications 446

Chapter 29

NSHTTPURLResponse Class Reference 449Overview 449 Adopted Protocols 449

72008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Tasks 450 Class Methods 450 Instance Methods 450 Chapter 30

NSIndexPath Class Reference 453Overview 453 Adopted Protocols 454 Tasks 454 Class Methods 455 Instance Methods 456

Chapter 31

NSIndexSet Class Reference 461Overview 461 Adopted Protocols 462 Tasks 462 Class Methods 463 Instance Methods 465

Chapter 32

NSInputStream Class Reference 473Overview 473 Tasks 474 Class Methods 474 Instance Methods 475

Chapter 33

NSInvocation Class Reference 479Overview 479 Adopted Protocols 480 Tasks 480 Class Methods 481 Instance Methods 481

Chapter 34

NSInvocationOperation Class Reference 489Overview 489 Tasks 489 Instance Methods 490 Constants 491

Chapter 35

NSKeyedArchiver Class Reference 493Overview 493 Tasks 494

82008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Class Methods 495 Instance Methods 497 Delegate Methods 504 Constants 507 Chapter 36

NSKeyedUnarchiver Class Reference 509Overview 509 Tasks 510 Class Methods 511 Instance Methods 513 Delegate Methods 520 Constants 522

Chapter 37

NSLocale Class Reference 525Overview 525 Tasks 526 Class Methods 527 Instance Methods 533 Constants 535 Notifications 538

Chapter 38

NSLock Class Reference 539Overview 539 Adopted Protocols 539 Tasks 540 Instance Methods 540

Chapter 39

NSMachPort Class Reference 543Overview 543 Tasks 543 Class Methods 544 Instance Methods 545 Delegate Methods 547 Constants 548

Chapter 40

NSMessagePort Class Reference 549Overview 549

Chapter 41

NSMethodSignature Class Reference 551Overview 551

92008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Tasks 552 Class Methods 552 Instance Methods 553 Chapter 42

NSMutableArray Class Reference 557Overview 557 Tasks 558 Class Methods 560 Instance Methods 560

Chapter 43

NSMutableCharacterSet Class Reference 577Overview 577 Tasks 577 Instance Methods 578

Chapter 44

NSMutableData Class Reference 583Overview 583 Tasks 584 Class Methods 585 Instance Methods 586

Chapter 45

NSMutableDictionary Class Reference 593Class at a Glance 593 Overview 594 Tasks 594 Class Methods 595 Instance Methods 596

Chapter 46

NSMutableIndexSet Class Reference 601Overview 601 Tasks 601 Instance Methods 602

Chapter 47

NSMutableSet Class Reference 607Overview 607 Tasks 608 Class Methods 608 Instance Methods 609

102008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 48

NSMutableString Class Reference 615Overview 615 Tasks 615 Class Methods 616 Instance Methods 617

Chapter 49

NSMutableURLRequest Class Reference 623Overview 623 Tasks 623 Instance Methods 624

Chapter 50

NSNetService Class Reference 631Overview 631 Tasks 632 Class Methods 634 Instance Methods 635 Delegate Methods 645 Constants 648

Chapter 51

NSNetServiceBrowser Class Reference 651Overview 651 Tasks 652 Instance Methods 653 Delegate Methods 657

Chapter 52

NSNotification Class Reference 663Overview 663 Adopted Protocols 664 Tasks 664 Class Methods 665 Instance Methods 666

Chapter 53

NSNotificationCenter Class Reference 669Class at a Glance 669 Overview 671 Tasks 671 Class Methods 672 Instance Methods 673

112008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 54

NSNotificationQueue Class Reference 677Overview 677 Tasks 677 Class Methods 678 Instance Methods 678 Constants 680

Chapter 55

NSNull Class Reference 683Overview 683 Adopted Protocols 683 Tasks 683 Class Methods 684

Chapter 56

NSNumber Class Reference 685Overview 685 Tasks 686 Class Methods 689 Instance Methods 695

Chapter 57

NSNumberFormatter Class Reference 709Overview 709 Tasks 710 Class Methods 717 Instance Methods 718 Constants 762

Chapter 58

NSObject Class Reference 767Overview 767 Adopted Protocols 769 Tasks 769 Class Methods 773 Instance Methods 787

Chapter 59

NSOperation Class Reference 807Overview 807 Tasks 810 Instance Methods 811 Constants 818

122008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 60

NSOperationQueue Class Reference 821Overview 821 Tasks 822 Instance Methods 823 Constants 826

Chapter 61

NSOutputStream Class Reference 827Overview 827 Tasks 828 Class Methods 828 Instance Methods 830

Chapter 62

NSPipe Class Reference 833Overview 833 Tasks 833 Class Methods 834 Instance Methods 834

Chapter 63

NSPort Class Reference 837Overview 837 Adopted Protocols 838 Tasks 838 Class Methods 839 Instance Methods 840 Delegate Methods 844 Notifications 844

Chapter 64

NSProcessInfo Class Reference 847Overview 847 Tasks 847 Class Methods 848 Instance Methods 849 Constants 853

Chapter 65

NSPropertyListSerialization Class Reference 855Overview 855 Tasks 855 Class Methods 856 Constants 858

132008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 66

NSProxy Class Reference 861Overview 861 Adopted Protocols 861 Tasks 862 Class Methods 863 Instance Methods 864

Chapter 67

NSRecursiveLock Class Reference 867Overview 867 Adopted Protocols 867 Tasks 867 Instance Methods 868

Chapter 68

NSRunLoop Class Reference 871Overview 871 Tasks 872 Class Methods 873 Instance Methods 874 Constants 881

Chapter 69

NSScanner Class Reference 883Overview 883 Adopted Protocols 884 Tasks 884 Class Methods 885 Instance Methods 886

Chapter 70

NSSet Class Reference 901Overview 901 Adopted Protocols 902 Tasks 903 Class Methods 905 Instance Methods 908

Chapter 71

NSSortDescriptor Class Reference 923Overview 923 Adopted Protocols 924 Tasks 924 Instance Methods 925

142008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 72

NSStream Class Reference 929Overview 929 Tasks 930 Instance Methods 931 Delegate Methods 935 Constants 936

Chapter 73

NSString Class Reference 943Overview 943 Adopted Protocols 946 Tasks 946 Class Methods 955 Instance Methods 964 Constants 1029

Chapter 74

NSThread Class Reference 1037Overview 1037 Tasks 1038 Class Methods 1040 Instance Methods 1044 Notifications 1050

Chapter 75

NSTimer Class Reference 1053Overview 1053 Tasks 1054 Class Methods 1055 Instance Methods 1058

Chapter 76

NSTimeZone Class Reference 1063Overview 1063 Adopted Protocols 1064 Tasks 1064 Class Methods 1066 Instance Methods 1071 Constants 1078 Notifications 1079

Chapter 77

NSURL Class Reference 1081Overview 1081 Adopted Protocols 1082

152008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Tasks 1082 Class Methods 1084 Instance Methods 1086 Constants 1095 Chapter 78

NSURLAuthenticationChallenge Class Reference 1097Overview 1097 Tasks 1097 Instance Methods 1098

Chapter 79

NSURLCache Class Reference 1103Overview 1103 Tasks 1103 Class Methods 1104 Instance Methods 1106

Chapter 80

NSURLConnection Class Reference 1111Overview 1111 Tasks 1112 Class Methods 1114 Instance Methods 1116 Delegate Methods 1119

Chapter 81

NSURLCredential Class Reference 1125Overview 1125 Adopted Protocols 1125 Tasks 1125 Class Methods 1126 Instance Methods 1127 Constants 1129

Chapter 82

NSURLCredentialStorage Class Reference 1131Overview 1131 Tasks 1131 Class Methods 1132 Instance Methods 1132 Notifications 1135

Chapter 83

NSURLProtectionSpace Class Reference 1137Overview 1137

162008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Adopted Protocols 1137 Tasks 1137 Instance Methods 1138 Constants 1142 Chapter 84

NSURLProtocol Class Reference 1145Overview 1145 Tasks 1146 Class Methods 1147 Instance Methods 1151

Chapter 85

NSURLRequest Class Reference 1155Overview 1155 Adopted Protocols 1155 Tasks 1156 Class Methods 1157 Instance Methods 1158 Constants 1163

Chapter 86

NSURLResponse Class Reference 1165Overview 1165 Adopted Protocols 1165 Tasks 1166 Instance Methods 1166 Constants 1169

Chapter 87

NSUserDefaults Class Reference 1171Overview 1171 Tasks 1172 Class Methods 1174 Instance Methods 1175 Constants 1192 Notifications 1193

Chapter 88

NSValue Class Reference 1195Overview 1195 Adopted Protocols 1195 Tasks 1196 Class Methods 1197 Instance Methods 1199

172008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Chapter 89

NSXMLParser Class Reference 1203Overview 1203 Tasks 1203 Instance Methods 1206 Delegate Methods 1213 Constants 1223

Part II Chapter 90

Protocols 1237 NSCoding Protocol Reference 1239Overview 1239 Tasks 1239 Instance Methods 1240

Chapter 91

NSCopying Protocol Reference 1241Overview 1241 Tasks 1242 Instance Methods 1242

Chapter 92

NSDecimalNumberBehaviors Protocol Reference 1243Overview 1243 Tasks 1243 Instance Methods 1244 Constants 1245

Chapter 93

NSErrorRecoveryAttempting Protocol Reference 1249Overview 1249 Tasks 1249 Instance Methods 1249

Chapter 94

NSFastEnumeration Protocol Reference 1253Overview 1253 Tasks 1253 Instance Methods 1253 Constants 1254

Chapter 95

NSKeyValueCoding Protocol Reference 1257Overview 1257

182008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Tasks 1257 Class Methods 1258 Instance Methods 1259 Constants 1267 Chapter 96

NSKeyValueObserving Protocol Reference 1271Overview 1271 Tasks 1271 Class Methods 1272 Instance Methods 1274 Constants 1280

Chapter 97

NSLocking Protocol Reference 1285Overview 1285 Tasks 1285 Instance Methods 1285

Chapter 98

NSMutableCopying Protocol Reference 1287Overview 1287 Tasks 1287 Instance Methods 1288

Chapter 99

NSObject Protocol Reference 1289Overview 1289 Tasks 1289 Instance Methods 1291

Chapter 100

NSURLAuthenticationChallengeSender Protocol Reference 1303Overview 1303 Tasks 1303 Instance Methods 1304

Chapter 101

NSURLProtocolClient Protocol Reference 1307Overview 1307 Tasks 1307 Instance Methods 1308

192008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CONTENTS

Part III Chapter 102

Functions 1313 Foundation Functions Reference 1315Overview 1315 Functions by Task 1315 Functions 1322

Part IV Chapter 103

Data Types 1387 Foundation Data Types Reference 1389Overview 1389 Data Types 1389

Part V Chapter 104

Constants 1399 Foundation Constants Reference 1401Overview 1401 Constants 1401

Document Revision History 1423 Index 1425

202008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

Figures and TablesIntroduction

The Foundation Framework 23Figure I-1 Cocoa Objective-C Hierarchy for Foundation 25

Chapter 30

NSIndexPath Class Reference 453Figure 30-1 Index path 1.4.3.2 454

Chapter 53

NSNotificationCenter Class Reference 669Table 53-1 Table 53-2 Types of dispatch table entries 670 Example notification dispatch table 670

212008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

FIGURES AND TABLES

222008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

INTRODUCTION

The Foundation Framework

Framework Header file directories Declared in

/System/Library/Frameworks/Foundation.framework /System/Library/Frameworks/Foundation.framework/Headers CALayer.h FoundationErrors.h NSArray.h NSAutoreleasePool.h NSBundle.h NSByteOrder.h NSCalendar.h NSCharacterSet.h NSCoder.h NSData.h NSDate.h NSDateFormatter.h NSDecimal.h NSDecimalNumber.h NSDictionary.h NSEnumerator.h NSError.h NSException.h NSFileHandle.h NSFileManager.h NSFormatter.h NSHTTPCookie.h NSHTTPCookieStorage.h NSIndexPath.h NSIndexSet.h NSInvocation.h NSKeyValueCoding.h NSKeyValueObserving.h NSKeyedArchiver.h NSLocale.h NSLock.h NSMethodSignature.h NSNetServices.h NSNotification.h NSNotificationQueue.h NSNull.h NSNumberFormatter.h NSObjCRuntime.h NSObject.h NSOperation.h NSPathUtilities.h NSPort.h NSProcessInfo.h

232008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

INTRODUCTION

The Foundation Framework

NSPropertyList.h NSProxy.h NSRange.h NSRunLoop.h NSScanner.h NSSet.h NSSortDescriptor.h NSStream.h NSString.h NSThread.h NSTimeZone.h NSTimer.h NSURL.h NSURLAuthenticationChallenge.h NSURLCache.h NSURLConnection.h NSURLCredential.h NSURLCredentialStorage.h NSURLError.h NSURLProtectionSpace.h NSURLProtocol.h NSURLRequest.h NSURLResponse.h NSUserDefaults.h NSValue.h NSXMLParser.h NSZone.h

IntroductionThe Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind:

Provide a small set of basic utility classes. Make software development easier by introducing consistent conventions for things such as deallocation. Support Unicode strings, object persistence, and object distribution. Provide a level of OS independence, to enhance portability.

The Foundation framework includes the root object class, classes representing basic data types such as strings and byte arrays, collection classes for storing other objects, classes representing system information such as dates, and classes representing communication ports. See Figure I-1 (page 25) for a list of those classes that make up the Foundation framework.

24

Introduction2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

INTRODUCTION

The Foundation Framework

The Foundation framework introduces several paradigms to avoid confusion in common situations, and to introduce a level of consistency across class hierarchies. This consistency is done with some standard policies, such as that for object ownership (that is, who is responsible for disposing of objects), and with abstract classes like NSEnumerator. These new paradigms reduce the number of special and exceptional cases in an API and allow you to code more efficiently by reusing the same mechanisms with various kinds of objects.

Foundation Framework ClassesThe Foundation class hierarchy is rooted in the Foundation frameworks NSObject class (see Figure I-1 (page 25)). The remainder of the Foundation framework consists of several related groups of classes as well as a few individual classes. Many of the groups form what are called class clustersabstract classes that work as umbrella interfaces to a versatile set of private subclasses. NSString and NSMutableString, for example, act as brokers for instances of various private subclasses optimized for different kinds of storage needs. Depending on the method you use to create a string, an instance of the appropriate optimized class will be returned to you. Note: In the following class-hierarchy diagrams, blue-shaded areas include classes that are available in Mac OS X and iPhone OS; gray-shaded areas include classes that are available in Mac OS X only. Figure I-1 Cocoa Objective-C Hierarchy for FoundationNSAffineTransform NSCalendar NSData NSMutableData NSDate NSCalendarDate NSDateComponents NSDecimalNumberHandler NSLocale NSNull NSTimeZone NSValue NSNumber NSDecimalNumber NSValueTransformer NSXMLNode NSXMLParser NSXMLDocument NSXMLDTD NSXMLDTDNode NSXMLElement NSMutableAttributedString NSMutableCharacterSet NSMutableString NSDateFormatter NSNumberFormatter NSMutableArray NSMutableDictionary NSDirectoryEnumerator NSMutableIndexSetXML Value Objects

NSObject

NSAttributedString NSCharacterSet NSString NSFormatter NSScanner NSSortDescriptor NSArray NSDictionary NSEnumerator NSHashTable NSIndexPath NSIndexSet NSMapTable NSPointerArray NSPointerFunctions NSSet NSExpression NSPredicate

Strings

Collections

NSMutableSet

NSCountedSetPredicates

NSComparisonPredicate NSCompoundPredicate

Introduction2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

25

INTRODUCTION

The Foundation Framework

Objective-C Foundation ContinuedNSError NSHost NSNetService NSNetServiceBrowser NSProcessInfo NSRunLoop NSSpellServer NSTimer NSUserDefaults File System NSBundle NSFileHandle NSFileManager NSMetadataItem NSMetadataQuery NSMetadataQueryAttributeValueTuple NSMetadataQueryResultGroup NSInputStream NSStream NSOutputStream NSCachedURLResponse NSHTTPCookie NSHTTPCookieStorage NSURL NSURLAuthorizationChallenge NSURLCache NSURLConnection NSURLCredential NSURLCredentialStorage NSURLDownload NSURLProtectionSpace NSURLProtocol NSURLRequest NSMutableURLRequest NSHTTPURLResponse NSURLResponse NSPipe NSPort NSPortMessage NSPortNameServerURL Operating-System Services

NSObject

NSMachPort NSMessagePort NSSocketPort NSMachBootstrapServer NSMessagePortNameServer NSSocketPortNameServer

Interprocess Communication

NSConditionLock NSDistributedLock NSLock NSOperation NSOperationQueue NSRecursiveLock NSTask NSThread

Locking/Threading

NSInvocationOperation

26

Introduction2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

INTRODUCTION

The Foundation Framework

Objective-C Foundation ContinuedNSNotification NSNotificationCenter NSNotificationQueue NSCoder NSPropertyListSerializationNotifications

NSDistributedNotificationCenterArchiving and Serialization

NSArchiver NSKeyedArchiver NSKeyedUnarchiver NSPortCoder NSUnarchiver

NSObject

NSAssertionHandler NSAutoreleasePool NSClassDescription NSException NSGarbageCollector NSInvocation NSMethodSignature NSUndoManager NSAppleEventDescriptor NSAppleEventManager NSAppleScript NSPositionalSpecifier NSScriptCoercionHandler NSScriptCommand

Objective-C Language Services

NSScriptCommandDescription NSScriptExecutionContext NSScriptObjectSpecifier NSScriptSuiteRegistry NSScriptWhoseTest

NSScriptClassDescription NSCloneCommand NSCloseCommand NSCountCommand NSCreateCommand NSDeleteCommand NSExistsCommand NSGetCommand NSMoveCommand NSQuitCommand NSSetCommand NSIndexSpecifier NSMiddleSpecifier NSNameSpecifier NSPropertySpecifier NSRandomSpecifier NSRangeSpecifier NSRelativeSpecifier NSUniqueIDSpecifier NSWhoseSpecifier NSLogicalTest NSSpecifierTestDistributed Objects

Scripting

NSProxy

NSConnection NSDistantObjectRequest NSDistantObject NSProtocolChecker

Many of these classes have closely related functionality:

Data storage. NSData and NSString provide object-oriented storage for arrays of bytes. NSValue and NSNumber provide object-oriented storage for arrays of simple C data values. NSArray, NSDictionary, and NSSet provide storage for Objective-C objects of any class. Text and strings. NSCharacterSet represents various groupings of characters that are used by the NSString and NSScanner classes. The NSString classes represent text strings and provide methods for searching, combining, and comparing strings. An NSScanner object is used to scan numbers and words from an NSString object. Dates and times. The NSDate, NSTimeZone, and NSCalendar classes store times and dates and represent calendrical information. They offer methods for calculating date and time differences. Together with NSLocale, they provide methods for displaying dates and times in many formats, and for adjusting times and dates based on location in the world.

Introduction2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

27

INTRODUCTION

The Foundation Framework

Application coordination and timing. NSNotification, NSNotificationCenter, and NSNotificationQueue provide systems that an object can use to notify all interested observers of changes that occur. You can use an NSTimer object to send a message to another object at specific intervals. Object creation and disposal. NSAutoreleasePool is used to implement the delayed-release feature of the Foundation framework. Object distribution and persistence. The data that an object contains can be represented in an architecture-independent way using NSPropertyListSerialization. The NSCoder and its subclasses take this process a step further by allowing class information to be stored along with the data. The resulting representations are used for archiving and for object distribution. Operating-system services. Several classes are designed to insulate you from the idiosyncrasies of various operating systems. NSFileManager provides a consistent interface for file operations (creating, renaming, deleting, and so on). NSThread and NSProcessInfo let you create multithreaded applications and query the environment in which an application runs. URL loading system. A set of classes and protocols provide access to common Internet protocols.

28

Introduction2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

PART I

Classes

292008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

PART I

Classes

302008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

Inherits from Conforms to

NSObject NSCoding NSCopying NSMutableCopying NSFastEnumeration NSObject (NSObject) /System/Library/Frameworks/Foundation.framework Available in iPhone OS 2.0 and later. Foundation/NSArray.h Foundation/NSKeyValueCoding.h Foundation/NSKeyValueObserving.h Foundation/NSPathUtilities.h Foundation/NSPredicate.h Foundation/NSSortDescriptor.h Collections Programming Topics for Cocoa Key-Value Coding Programming Guide Property List Programming Guide Predicate Programming Guide DrillDownSave EditableDetailView TableViewSuite TheElements UICatalog

Framework Availability Declared in

Companion guides

Related sample code

OverviewNSArray and its subclass NSMutableArray manage collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays.

The NSArray and NSMutableArray classes adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert an array of one type to the other.NSArray and NSMutableArray are part of a class cluster, so arrays are not actual instances of the NSArray or NSMutableArray classes but of one of their private subclasses. Although an arrays class is private, its interface is public, as declared by these abstract superclasses, NSArray and NSMutableArray.

Overview2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

31

CHAPTER 1

NSArray Class Reference

NSArrays two primitive methodscount (page 45) and objectAtIndex: (page 55)provide the basis for all other methods in its interface. The count method returns the number of elements in the array; objectAtIndex: gives you access to the array elements by index, with index values starting at 0.

The methods objectEnumerator (page 56) and reverseObjectEnumerator (page 58) also grant sequential access to the elements of the array, differing only in the direction of travel through the elements. These methods are provided so that arrays can be traversed in a manner similar to that used for objects of other collection classes, such as NSDictionary. See the objectEnumerator method description for a code excerpt that shows how to use these methods to access the elements of an array. In Mac OS X v10.5 and later, it is more efficient to use the fast enumeration protocol (see NSFastEnumeration).NSArray provides methods for querying the elements of the array. The indexOfObject: (page 48) method

searches the array for the object that matches its argument. To determine whether the search is successful, each element of the array is sent an isEqual: (page 1293) message, as declared in the NSObject protocol. Another method, indexOfObjectIdenticalTo: (page 49), is provided for the less common case of determining whether a specific object is present in the array. The indexOfObjectIdenticalTo: method tests each element in the array to see whether its id matches that of the argument.NSArrays filteredArrayUsingPredicate: method allows you to create a new array from an existing

array filtered using a predicate (see Predicate Programming Guide).NSArrays makeObjectsPerformSelector: (page 54) and makeObjectsPerformSelector:withObject: (page 55) methods let you send messages to all objects

in the array. To act on the array as a whole, a variety of other methods are defined. You can create a sorted version of the array (sortedArrayUsingSelector: (page 62) and sortedArrayUsingFunction:context: (page 60), extract a subset of the array (subarrayWithRange: (page 63)), or concatenate the elements of an array of NSString objects into a single string (componentsJoinedByString: (page 44)). In addition, you can compare two arrays using the isEqualToArray: (page 54) and firstObjectCommonWithArray: (page 47) methods. Finally, you can create new arrays that contain the objects in an existing array and one or more additional objects with arrayByAddingObject: (page 43) and arrayByAddingObjectsFromArray: (page 43). Arrays maintain strong references to their contentsin a managed memory environment, each object receives a retain message before its id is added to the array and a release message when it is removed from the array or when the array is deallocated. If you want a collection with different object ownership semantics, consider using CFArray Reference, NSPointerArray, or NSHashTable instead.NSArray is toll-free bridged with its Core Foundation counterpart, CFArray Reference. What this means is

that the Core Foundation type is interchangeable in function or method calls with the bridged Foundation object, providing you cast one type to the other. Therefore, in an API where you see an NSArray * parameter, you can pass in a CFArrayRef, and in an API where you see a CFArrayRef parameter, you can pass in an NSArray instance. This arrangement also applies to your concrete subclasses of NSArray. See Carbon-Cocoa Integration Guide for more information on toll-free bridging.

Subclassing NotesMost developers would not have any reason to subclass NSArray. The class does well what it is designed to domaintain an ordered collection of objects. But there are situations where a custom NSArray object might come in handy. Here are a few possibilities:

Changing how NSArray stores the elements of its collection. You might do this for performance reasons or for better compatibility with legacy code.

32

Overview2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

Changing how NSArray retains and releases its elements. Acquiring more information about what is happening to the collection (for example, statistics gathering).

Methods to OverrideAny subclass of NSArray must override the primitive instance methods count (page 45) and objectAtIndex: (page 55). These methods must operate on the backing store that you provide for the elements of the collection. For this backing store you can use a static array, a standard NSArray object, or some other data type or mechanism. You may also choose to override, partially or fully, any other NSArray method for which you want to provide an alternative implementation. You might want to implement an initializer for your subclass that is suited to the backing store that the subclass is managing. The NSArray class does not have a designated initializer, so your initializer need only invoke the init (page 794) method of super. The NSArray class adopts the NSCopying, NSMutableCopying, and NSCoding protocols; if you want instances of your own custom subclass created from copying or coding, override the methods in these protocols. Remember that NSArray is the public interface for a class cluster and what this entails for your subclass. The primitive methods of NSArray do not include any designated initializers. This means that you must provide the storage for your subclass and implement the primitive methods that directly act on that storage.

Special ConsiderationsIn most cases your custom NSArray class should conform to Cocoas object-ownership conventions. Thus you must send retain (page 1299) to each object that you add to your collection and release (page 1298) to each object that you remove from the collection. Of course, if the reason for subclassing NSArray is to implement object-retention behavior different from the norm (for example, a non-retaining array), then you can ignore this requirement.

Alternatives to SubclassingBefore making a custom class of NSArray, investigate NSPointerArray, NSHashTable, and the corresponding Core Foundation type, CFArray Reference. Because NSArray and CFArray are toll-free bridged, you can substitute a CFArray object for a NSArray object in your code (with appropriate casting). Although they are corresponding types, CFArray and NSArray do not have identical interfaces or implementations, and you can sometimes do things with CFArray that you cannot easily do with NSArray. For example, CFArray provides a set of callbacks, some of which are for implementing custom retain-release behavior. If you specify NULL implementations for these callbacks, you can easily get a non-retaining array. If the behavior you want to add supplements that of the existing class, you could write a category on NSArray. Keep in mind, however, that this category will be in effect for all instances of NSArray that you use, and this might have unintended consequences.

Adopted ProtocolsNSCoding encodeWithCoder: (page 1240) initWithCoder: (page 1240)

Adopted Protocols2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

33

CHAPTER 1

NSArray Class Reference

NSCopying copyWithZone: (page 1242)

NSMutableCopying mutableCopyWithZone: (page 1288)

TasksCreating an Array+ array (page 37)

Creates and returns an empty array.+ arrayWithArray: (page 38)

Creates and returns an array containing the objects in another given array.+ arrayWithContentsOfFile: (page 38)

Creates and returns an array containing the contents of the file specified by a given path.+ arrayWithContentsOfURL: (page 39)

Creates and returns an array containing the contents specified by a given URL.+ arrayWithObject: (page 40)

Creates and returns an array containing a given object.+ arrayWithObjects: (page 40)

Creates and returns an array containing the objects in the argument list.+ arrayWithObjects:count: (page 41)

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

Initializing an Array initWithArray: (page 50)

Initializes a newly allocated array by placing in it the objects contained in a given array. initWithArray:copyItems: (page 51)

Initializes a newly allocated array using anArray as the source of data objects for the array. initWithContentsOfFile: (page 51)

Initializes a newly allocated array with the contents of the file specified by a given path. initWithContentsOfURL: (page 52)

Initializes a newly allocated array with the contents of the location specified by a given URL. initWithObjects: (page 52)

Initializes a newly allocated array by placing in it the objects in the argument list. initWithObjects:count: (page 53)

Initializes a newly allocated array to include a given number of objects from a given C array.

34

Tasks2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

Querying an Array containsObject: (page 44)

Returns a Boolean value that indicates whether a given object is present in the receiver. count (page 45)

Returns the number of objects currently in the receiver. getObjects: (page 47)

Copies all the objects contained in the receiver to aBuffer. getObjects:range: (page 48)

Copies the objects contained in the receiver that fall within the specified range to aBuffer. indexOfObject: (page 48)

Returns the lowest index whose corresponding array value is equal to a given object. indexOfObject:inRange: (page 49)

Returns the lowest index within a specified range whose corresponding array value is equal to a given object . indexOfObjectIdenticalTo: (page 49)

Returns the lowest index whose corresponding array value is identical to a given object. indexOfObjectIdenticalTo:inRange: (page 50)

Returns the lowest index within a specified range whose corresponding array value is equal to a given object . lastObject (page 54)

Returns the object in the array with the highest index value. objectAtIndex: (page 55)

Returns the object located at index. objectsAtIndexes: (page 57)

Returns an array containing the objects in the receiver at the indexes specified by a given index set. objectEnumerator (page 56)

Returns an enumerator object that lets you access each object in the receiver. reverseObjectEnumerator (page 58)

Returns an enumerator object that lets you access each object in the receiver, in reverse order.

Sending Messages to Elements makeObjectsPerformSelector: (page 54)

Sends to each object in the receiver the message identified by a given selector, starting with the first object and continuing through the array to the last object. makeObjectsPerformSelector:withObject: (page 55) Sends the aSelector message to each object in the array, starting with the first object and continuing

through the array to the last object.

Comparing Arrays firstObjectCommonWithArray: (page 47)

Returns the first object contained in the receiver thats equal to an object in another given array.

Tasks2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

35

CHAPTER 1

NSArray Class Reference

isEqualToArray: (page 54)

Compares the receiving array to another array.

Deriving New Arrays arrayByAddingObject: (page 43)

Returns a new array that is a copy of the receiver with a given object added to the end. arrayByAddingObjectsFromArray: (page 43)

Returns a new array that is a copy of the receiver with the objects contained in another array added to the end. subarrayWithRange: (page 63)

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

Sorting sortedArrayHint (page 59)

Analyzes the receiver and returns a hint that speeds the sorting of the array when the hint is supplied to sortedArrayUsingFunction:context:hint: (page 61). sortedArrayUsingFunction:context: (page 60)

Returns a new array that lists the receivers elements in ascending order as defined by the comparison function comparator. sortedArrayUsingFunction:context:hint: (page 61)

Returns a new array that lists the receivers elements in ascending order as defined by the comparison function comparator. sortedArrayUsingDescriptors: (page 60)

Returns a copy of the receiver sorted as specified by a given array of sort descriptors. sortedArrayUsingSelector: (page 62)

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

Working with String Elements componentsJoinedByString: (page 44) Constructs and returns an NSString object that is the result of interposing a given separator between

the elements of the receivers array.

Creating a Description description (page 45)

Returns a string that represents the contents of the receiver, formatted as a property list. descriptionWithLocale: (page 46)

Returns a string that represents the contents of the receiver, formatted as a property list.

36

Tasks2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

descriptionWithLocale:indent: (page 46)

Returns a string that represents the contents of the receiver, formatted as a property list. writeToFile:atomically: (page 64)

Writes the contents of the receiver to a file at a given path. writeToURL:atomically: (page 64)

Writes the contents of the receiver to the location specified by a given URL.

Collecting Paths pathsMatchingExtensions: (page 57)

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

Key-Value Observing addObserver:forKeyPath:options:context: (page 41)

Raises an exception. removeObserver:forKeyPath: (page 58)

Raises an exception. addObserver:toObjectsAtIndexes:forKeyPath:options:context: (page 42) Registers anObserver to receive key value observer notifications for the specified keypath relative to the objects at indexes. removeObserver:fromObjectsAtIndexes:forKeyPath: (page 58) Removes anObserver from all key value observer notifications associated with the specified keyPath relative to the receivers objects at indexes.

Key-Value Coding setValue:forKey: (page 59) Invokes setValue:forKey: on each of the receiver's items using the specified value and key. valueForKey: (page 63)

Returns an array containing the results of invoking valueForKey: using key on each of the receiver's objects.

Class MethodsarrayCreates and returns an empty array.+ (id)array

Class Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

37

CHAPTER 1

NSArray Class Reference

Return Value An empty array. Discussion This method is used by mutable subclasses of NSArray. Availability Available in iPhone OS 2.0 and later. See Also+ arrayWithObject: (page 40) + arrayWithObjects: (page 40)

Related Sample Code BonjourWeb SeismicXML TableViewSuite TheElements XMLPerformance Declared InNSArray.h

arrayWithArray:Creates and returns an array containing the objects in another given array.+ (id)arrayWithArray:(NSArray *)anArray

ParametersanArray

An array. Return Value An array containing the objects in anArray. Availability Available in iPhone OS 2.0 and later. See Also+ arrayWithObjects: (page 40) initWithObjects: (page 52)

Declared InNSArray.h

arrayWithContentsOfFile:Creates and returns an array containing the contents of the file specified by a given path.+ (id)arrayWithContentsOfFile:(NSString *)aPath

38

Class Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

ParametersaPath

The path to a file containing a string representation of an array produced by the writeToFile:atomically: (page 64) method. Return Value An array containing the contents of the file specified by aPath. Returns nil if the file cant be opened or if the contents of the file cant be parsed into an array. Discussion The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). Availability Available in iPhone OS 2.0 and later. See Also writeToFile:atomically: (page 64)

Related Sample Code Accessory GLPaint TouchCells Declared InNSArray.h

arrayWithContentsOfURL:Creates and returns an array containing the contents specified by a given URL.+ (id)arrayWithContentsOfURL:(NSURL *)aURL

ParametersaURL

The location of a file containing a string representation of an array produced by the writeToURL:atomically: (page 64) method. Return Value An array containing the contents specified by aURL. Returns nil if the location cant be opened or if the contents of the location cant be parsed into an array. Discussion The array representation at the location identified by aURL must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). Availability Available in iPhone OS 2.0 and later. See Also writeToURL:atomically: (page 64)

Declared InNSArray.h

Class Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

39

CHAPTER 1

NSArray Class Reference

arrayWithObject:Creates and returns an array containing a given object.+ (id)arrayWithObject:(id)anObject

ParametersanObject

An object. Return Value An array containing the single element anObject. Availability Available in iPhone OS 2.0 and later. See Also+ array (page 37) + arrayWithObjects: (page 40)

Related Sample Code BonjourWeb EditableDetailView SQLite Book List TableViewSuite TheElements Declared InNSArray.h

arrayWithObjects:Creates and returns an array containing the objects in the argument list.+ (id)arrayWithObjects:(id)firstObj, ...

ParametersfirstObj, ...

A comma-separated list of objects ending with 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];

Availability Available in iPhone OS 2.0 and later.

40

Class Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

See Also+ array (page 37) + arrayWithObject: (page 40)

Related Sample Code EditableDetailView NavBar PVRTextureLoader UICatalog ViewTransitions Declared InNSArray.h

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

Parametersobjects

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 arrayit 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. Availability Available in iPhone OS 2.0 and later. See Also getObjects: (page 47) getObjects:range: (page 48)

Declared InNSArray.h

Instance MethodsaddObserver:forKeyPath:options:context:Raises an exception.

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

41

CHAPTER 1

NSArray Class Reference

- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context

Parametersobserver

The object to register for KVO notifications. The observer must implement the key-value observing method observeValueForKeyPath:ofObject:change:context: (page 1276).keyPath

The key path, relative to the receiver, of the property to observe. This value must not be nil.options

A combination of the NSKeyValueObservingOptions (page 1281) values that specifies what is included in observation notifications. For possible values, see NSKeyValueObservingOptions.context

Arbitrary data that is passed to observer inobserveValueForKeyPath:ofObject:change:context: (page 1276).

Special ConsiderationsNSArray objects are not observable, so this method raises an exception when invoked on an NSArray object.

Instead of observing an array, observe the to-many relationship for which the array is the collection of related objects. Availability Available in iPhone OS 2.0 and later. See Also removeObserver:forKeyPath: (page 58) addObserver:toObjectsAtIndexes:forKeyPath:options:context: (page 42)

Declared InNSKeyValueObserving.h

addObserver:toObjectsAtIndexes:forKeyPath:options:context:Registers anObserver to receive key value observer notifications for the specified keypath relative to the objects at indexes.- (void)addObserver:(NSObject *)anObserver toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context

Discussion The options determine what is included in the notifications, and the context is passed in the notifications. This is not merely a convenience method; invoking this method is potentially much faster than repeatedly invoking addObserver:forKeyPath:options:context: (page 1274). Availability Available in iPhone OS 2.0 and later. See Also removeObserver:fromObjectsAtIndexes:forKeyPath: (page 58)

42

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

Declared InNSKeyValueObserving.h

arrayByAddingObject:Returns a new array that is a copy of the receiver with a given object added to the end.- (NSArray *)arrayByAddingObject:(id)anObject

ParametersanObject

An object. Return Value A new array that is a copy of the receiver with anObject added to the end. Discussion If anObject is nil, an NSInvalidArgumentException is raised. Availability Available in iPhone OS 2.0 and later. See Also addObject: (page 560) (NSMutableArray)

Declared InNSArray.h

arrayByAddingObjectsFromArray:Returns a new array that is a copy of the receiver with the objects contained in another array added to the end.- (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray

ParametersotherArray

An array. Return Value A new array that is a copy of the receiver with the objects contained in otherArray added to the end. Availability Available in iPhone OS 2.0 and later. See Also addObjectsFromArray: (page 561) (NSMutableArray)

Declared InNSArray.h

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

43

CHAPTER 1

NSArray Class Reference

componentsJoinedByString:Constructs and returns an NSString object that is the result of interposing a given separator between the elements of the receivers array.- (NSString *)componentsJoinedByString:(NSString *)separator

Parametersseparator

The string to interpose between the elements of the receivers array. Return Value An NSString object that is the result of interposing separator between the elements of the receivers array. If the receiver 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 receivers array must handle description. Availability Available in iPhone OS 2.0 and later. See Also componentsSeparatedByString: (page 972) (NSString)

Declared InNSArray.h

containsObject:Returns a Boolean value that indicates whether a given object is present in the receiver.- (BOOL)containsObject:(id)anObject

ParametersanObject

An object. Return Value YES if anObject is present in the receiver, otherwise NO. Discussion This method determines whether anObject is present in the receiver by sending an isEqual: (page 1293) message to each of the receivers objects (and passing anObject as the parameter to each isEqual: message). Availability Available in iPhone OS 2.0 and later.

44

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

See Also indexOfObject: (page 48) indexOfObjectIdenticalTo: (page 49)

Declared InNSArray.h

countReturns the number of objects currently in the receiver.- (NSUInteger)count

Return Value The number of objects currently in the receiver. Availability Available in iPhone OS 2.0 and later. See Also objectAtIndex: (page 55)

Related Sample Code DrillDownSave PVRTextureLoader TableViewSuite TheElements ViewTransitions Declared InNSArray.h

descriptionReturns a string that represents the contents of the receiver, formatted as a property list.- (NSString *)description

Return Value A string that represents the contents of the receiver, formatted as a property list. Availability Available in iPhone OS 2.0 and later. See Also descriptionWithLocale: (page 46) descriptionWithLocale:indent: (page 46)

Declared InNSArray.h

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

45

CHAPTER 1

NSArray Class Reference

descriptionWithLocale:Returns a string that represents the contents of the receiver, formatted as a property list.- (NSString *)descriptionWithLocale:(id)locale

Parameterslocale

An NSLocale object or an NSDictionary object that specifies options used for formatting each of the receivers elements (where recognized). Specify nil if you dont want the elements formatted. Return Value A string that represents the contents of the receiver, formatted as a property list. Discussion For a description of how locale is applied to each element in the receiving array, see descriptionWithLocale:indent: (page 46). Availability Available in iPhone OS 2.0 and later. See Also description (page 45) descriptionWithLocale:indent: (page 46)

Declared InNSArray.h

descriptionWithLocale:indent:Returns a string that represents the contents of the receiver, formatted as a property list.- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level

Parameterslocale

An NSLocale object or an NSDictionary object that specifies options used for formatting each of the receivers elements (where recognized). Specify nil if you dont want the elements formatted.level

A level of indent, to make the output more readable: set level to 0 to use four spaces to indent, or 1 to indent the output with a tab character. Return Value A string that represents the contents of the receiver, formatted as a property list. Discussion The returned NSString object contains the string representations of each of the receivers elements, in order, from first to last. To obtain the string representation of a given element, descriptionWithLocale:indent: proceeds as follows:

If the element is an NSString object, it is used as is. If the element responds to descriptionWithLocale:indent:, that method is invoked to obtain the elements string representation.

46

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

If the element responds to descriptionWithLocale: (page 46), that method is invoked to obtain the elements string representation. If none of the above conditions is met, the elements string representation is obtained by invoking its description (page 45) method.

Availability Available in iPhone OS 2.0 and later. See Also description (page 45) descriptionWithLocale: (page 46)

Declared InNSArray.h

firstObjectCommonWithArray:Returns the first object contained in the receiver thats equal to an object in another given array.- (id)firstObjectCommonWithArray:(NSArray *)otherArray

ParametersotherArray

An array. Return Value Returns the first object contained in the receiver thats equal to an object in otherArray. If no such object is found, returns nil. Discussion This method uses isEqual: (page 1293) to check for object equality. Availability Available in iPhone OS 2.0 and later. See Also containsObject: (page 44)

Declared InNSArray.h

getObjects:Copies all the objects contained in the receiver to aBuffer.- (void)getObjects:(id *)aBuffer

Availability Available in iPhone OS 2.0 and later. See Also+ arrayWithObjects:count: (page 41)

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

47

CHAPTER 1

NSArray Class Reference

Declared InNSArray.h

getObjects:range:Copies the objects contained in the receiver that fall within the specified range to aBuffer.- (void)getObjects:(id *)aBuffer range:(NSRange)aRange

Availability Available in iPhone OS 2.0 and later. See Also+ arrayWithObjects:count: (page 41)

Related Sample Code SeismicXML TableViewSuite Declared InNSArray.h

indexOfObject:Returns the lowest index whose corresponding array value is equal to a given object.- (NSUInteger)indexOfObject:(id)anObject

ParametersanObject

An object. Return Value The lowest index whose corresponding array value is equal to anObject. If none of the objects in the receiver is equal to anObject, returns NSNotFound. Discussion Objects are considered equal if isEqual: (page 1293) returns YES. Availability Available in iPhone OS 2.0 and later. See Also containsObject: (page 44) indexOfObjectIdenticalTo: (page 49)

Related Sample Code LocateMe Declared InNSArray.h

48

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

indexOfObject:inRange:Returns the lowest index within a specified range whose corresponding array value is equal to a given object .- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range

ParametersanObject

An object.range

The range of indexes in the receiver within which to search for anObject. Return Value The lowest index within range whose corresponding array value is equal to anObject. If none of the objects within range is equal to anObject, returns NSNotFound. Discussion Objects are considered equal if isEqual: (page 1293) returns YES. Availability Available in iPhone OS 2.0 and later. See Also containsObject: (page 44) indexOfObjectIdenticalTo:inRange: (page 50)

Declared InNSArray.h

indexOfObjectIdenticalTo:Returns the lowest index whose corresponding array value is identical to a given object.- (NSUInteger)indexOfObjectIdenticalTo:(id)anObject

ParametersanObject

An object. Return Value The lowest index whose corresponding array value is identical to anObject. If none of the objects in the receiver is identical to anObject, returns NSNotFound. Discussion Objects are considered identical if their object addresses are the same. Availability Available in iPhone OS 2.0 and later. See Also containsObject: (page 44) indexOfObject: (page 48)

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

49

CHAPTER 1

NSArray Class Reference

Declared InNSArray.h

indexOfObjectIdenticalTo:inRange:Returns the lowest index within a specified range whose corresponding array value is equal to a given object .- (NSUInteger)indexOfObjectIdenticalTo:(id)anObject inRange:(NSRange)range

ParametersanObject

An object.range

The range of indexes in the receiver within which to search for anObject. Return Value The lowest index within range whose corresponding array value is identical to anObject. If none of the objects within range is identical to anObject, returns NSNotFound. Discussion Objects are considered identical if their object addresses are the same. Availability Available in iPhone OS 2.0 and later. See Also containsObject: (page 44) indexOfObject:inRange: (page 49)

Declared InNSArray.h

initWithArray:Initializes a newly allocated array by placing in it the objects contained in a given array.- (id)initWithArray:(NSArray *)anArray

ParametersanArray

An array. Return Value An array initialized to contain the objects in anArray. The returned object might be different than the original receiver. Discussion After an immutable array has been initialized in this way, it cannot be modified. Availability Available in iPhone OS 2.0 and later.

50

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

See Also+ arrayWithObject: (page 40) initWithObjects: (page 52)

Declared InNSArray.h

initWithArray:copyItems:Initializes a newly allocated array using anArray as the source of data objects for the array.- (id)initWithArray:(NSArray *)array copyItems:(BOOL)flag

Parametersarray

An array.flag

If YES, each object in array receives a copyWithZone: message to create a copy of the object. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned array. If NO, then in a managed memory environment each object in array simply receives a retain message as its added to the returned array. Return Value An array initialized to contain the objectsor if flag is YES, copies of the objectsin array. The returned object might be different than the original receiver. Discussion After an immutable array has been initialized in this way, it cannot be modified. Availability Available in iPhone OS 2.0 and later. See Also initWithArray: (page 50) + arrayWithObject: (page 40) initWithObjects: (page 52)

Declared InNSArray.h

initWithContentsOfFile:Initializes a newly allocated array with the contents of the file specified by a given path.- (id)initWithContentsOfFile:(NSString *)aPath

ParametersaPath

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

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

51

CHAPTER 1

NSArray Class Reference

Return Value An array initialized to contain the contents of the file specified by aPath or nil if the file cant be opened or the contents of the file cant be parsed into an array. The returned object might be different than the original receiver. Discussion The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). Availability Available in iPhone OS 2.0 and later. See Also+ arrayWithContentsOfFile: (page 38) writeToFile:atomically: (page 64)

Declared InNSArray.h

initWithContentsOfURL:Initializes a newly allocated array with the contents of the location specified by a given URL.- (id)initWithContentsOfURL:(NSURL *)aURL

ParametersaURL

The location of a file containing a string representation of an array produced by the writeToURL:atomically: (page 64) method. Return Value An array initialized to contain the contents specified by aURL. Returns nil if the location cant be opened or if the contents of the location cant be parsed into an array. The returned object might be different than the original receiver. Discussion The array representation at the location identified by aURL must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). Availability Available in iPhone OS 2.0 and later. See Also+ arrayWithContentsOfURL: (page 39) writeToURL:atomically: (page 64)

Declared InNSArray.h

initWithObjects:Initializes a newly allocated array by placing in it the objects in the argument list.

52

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

- (id)initWithObjects:(id)firstObj, ...

ParametersfirstObj, ...

A comma-separated list of objects ending with nil. Return Value An array initialized to include the objects in the argument list. The returned object might be different than the original receiver. Discussion After an immutable array has been initialized in this way, it cant be modified. Availability Available in iPhone OS 2.0 and later. See Also initWithObjects:count: (page 53) + arrayWithObjects: (page 40) initWithArray: (page 50)

Declared InNSArray.h

initWithObjects:count:Initializes a newly allocated array to include a given number of objects from a given C array.- (id)initWithObjects:(const id *)objects count:(NSUInteger)count

Parametersobjects

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 arrayit must not be negative or greater than the number of elements in objects. Return Value A newly allocated array including the first count objects from objects. The returned object might be different than the original receiver. Discussion Elements are added to the new array in the same order they appear in objects, up to but not including index count. After an immutable array has been initialized in this way, it cant be modified. Availability Available in iPhone OS 2.0 and later. See Also initWithObjects: (page 52) + arrayWithObjects: (page 40)

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

53

CHAPTER 1

NSArray Class Reference

initWithArray: (page 50)

Declared InNSArray.h

isEqualToArray:Compares the receiving array to another array.- (BOOL)isEqualToArray:(NSArray *)otherArray

ParametersotherArray

An array. Return Value YES if the contents of otherArray are equal to the contents of the receiver, otherwise NO. Discussion Two arrays have equal contents if they each hold the same number of objects and objects at a given index in each array satisfy the isEqual: (page 1293) test. Availability Available in iPhone OS 2.0 and later. Declared InNSArray.h

lastObjectReturns the object in the array with the highest index value.- (id)lastObject

Return Value The object in the array with the highest index value. If the array is empty, returns nil. Availability Available in iPhone OS 2.0 and later. See Also removeLastObject (page 565) (NSMutableArray)

Declared InNSArray.h

makeObjectsPerformSelector:Sends to each object in the receiver 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

54

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

ParametersaSelector

A selector that identifies the message to send to the objects in the receiver. The method must not take any arguments, and must not have the side effect of modifying the receiving array. Discussion This method raises an NSInvalidArgumentException if aSelector is NULL. Availability Available in iPhone OS 2.0 and later. See Also makeObjectsPerformSelector:withObject: (page 55)

Declared InNSArray.h

makeObjectsPerformSelector:withObject:Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object.- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject

ParametersaSelector

A selector that identifies the message to send to the objects in the receiver. The method must take a single argument of type id, and must not have the side effect of modifying the receiving array.anObject

The object to send as the argument to each invocation of the aSelector method. Discussion This method raises an NSInvalidArgumentException if aSelector is NULL. Availability Available in iPhone OS 2.0 and later. See Also makeObjectsPerformSelector: (page 54)

Declared InNSArray.h

objectAtIndex:Returns the object located at index.- (id)objectAtIndex:(NSUInteger)index

Parametersindex

An index within the bounds of the receiver.

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

55

CHAPTER 1

NSArray Class Reference

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. Availability Available in iPhone OS 2.0 and later. See Also count (page 45) objectsAtIndexes: (page 57)

Related Sample Code DrillDownSave PVRTextureLoader TableViewSuite TheElements ViewTransitions Declared InNSArray.h

objectEnumeratorReturns an enumerator object that lets you access each object in the receiver.- (NSEnumerator *)objectEnumerator

Return Value An enumerator object that lets you access each object in the receiver, in order, from the element at the lowest index upwards. Discussion Returns an enumerator object that lets you access each object in the receiver, 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. On Mac OS X v10.5 and later, it is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Availability Available in iPhone OS 2.0 and later.

56

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

See Also reverseObjectEnumerator (page 58) nextObject (page 336) (NSEnumerator)

Declared InNSArray.h

objectsAtIndexes:Returns an array containing the objects in the receiver at the indexes specified by a given index set.- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes

Return Value An array containing the objects in the receiver at the indexes specified by indexes. Discussion The returned objects are in the ascending order of their indexes in indexes, so that object in returned array with higher index in indexes will follow the object with smaller index in indexes. Raises an NSRangeException exception if any location in indexes exceeds the bounds of the receiver. Availability Available in iPhone OS 2.0 and later. See Also count (page 45) objectAtIndex: (page 55)

Declared InNSArray.h

pathsMatchingExtensions:Returns an array containing all the pathname elements in the receiver that have filename extensions from a given array.- (NSArray *)pathsMatchingExtensions:(NSArray *)filterTypes

ParametersfilterTypes

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 receiver that have filename extensions from the filterTypes array. Availability Available in iPhone OS 2.0 and later. Declared InNSPathUtilities.h

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

57

CHAPTER 1

NSArray Class Reference

removeObserver:forKeyPath:Raises an exception.- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath

Parametersobserver

The object to remove as an observer.keyPath

A key-path, relative to the receiver, for which observer is registered to receive KVO change notifications. This value must not be nil. Special ConsiderationsNSArray objects are not observable, so this method raises an exception when invoked on an NSArray object.

Instead of observing an array, observe the to-many relationship for which the array is the collection of related objects. Availability Available in iPhone OS 2.0 and later. See Also addObserver:forKeyPath:options:context: (page 41) removeObserver:fromObjectsAtIndexes:forKeyPath: (page 58)

Declared InNSKeyValueObserving.h

removeObserver:fromObjectsAtIndexes:forKeyPath:Removes anObserver from all key value observer notifications associated with the specified keyPath relative to the receivers objects at indexes.- (void)removeObserver:(NSObject *)anObserver fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath

Discussion This is not merely a convenience method; invoking this method is potentially much faster than repeatedly invoking removeObserver:forKeyPath: (page 1277). Availability Available in iPhone OS 2.0 and later. See Also addObserver:toObjectsAtIndexes:forKeyPath:options:context: (page 42)

Declared InNSKeyValueObserving.h

reverseObjectEnumeratorReturns an enumerator object that lets you access each object in the receiver, in reverse order.

58

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

- (NSEnumerator *)reverseObjectEnumerator

Return Value An enumerator object that lets you access each object in the receiver, in order, from the element at the highest index down to the element at index 0. Special Considerations When you use this method with mutable subclasses of NSArray, you must not modify the array during enumeration. On Mac OS X v10.5 and later, it is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Availability Available in iPhone OS 2.0 and later. See Also objectEnumerator (page 56) nextObject (page 336) (NSEnumerator)

Declared InNSArray.h

setValue:forKey:Invokes setValue:forKey: on each of the receiver's items using the specified value and key.- (void)setValue:(id)value forKey:(NSString *)key

Availability Available in iPhone OS 2.0 and later. See Also valueForKey: (page 63)

Declared InNSKeyValueCoding.h

sortedArrayHintAnalyzes the receiver and returns a hint that speeds the sorting of the array when the hint is supplied to sortedArrayUsingFunction:context:hint: (page 61).- (NSData *)sortedArrayHint

Availability Available in iPhone OS 2.0 and later. See Also sortedArrayUsingFunction:context:hint: (page 61)

Declared InNSArray.h

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

59

CHAPTER 1

NSArray Class Reference

sortedArrayUsingDescriptors:Returns a copy of the receiver sorted as specified by a given array of sort descriptors.- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors

ParameterssortDescriptors An array of NSSortDescriptor objects.

Return Value A copy of the receiver sorted as specified by sortDescriptors. Discussion The first descriptor specifies the primary key path to be used in sorting the receivers contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information. Availability Available in iPhone OS 2.0 and later. See Also sortedArrayUsingSelector: (page 62) sortedArrayUsingFunction:context: (page 60) sortedArrayUsingFunction:context:hint: (page 61)

Declared InNSSortDescriptor.h

sortedArrayUsingFunction:context:Returns a new array that lists the receivers elements in ascending order as defined by the comparison function comparator.- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

Discussion The new array contains references to the receivers elements, not copies of them. The comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, its passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive. Given anArray (an array of NSNumber objects) and a comparison function of this type:NSInteger intSort(id num1, id num2, void *context) { int v1 = [num1 intValue]; int v2 = [num2 intValue]; if (v1 < v2) return NSOrderedAscending; else if (v1 > v2)

60

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

return NSOrderedDescending; else return NSOrderedSame; }

A sorted version of anArray is created in this way:NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

Availability Available in iPhone OS 2.0 and later. See Also sortedArrayUsingDescriptors: (page 60) sortedArrayUsingFunction:context:hint: (page 61) sortedArrayUsingSelector: (page 62)

Declared InNSArray.h

sortedArrayUsingFunction:context:hint:Returns a new array that lists the receivers elements in ascending order as defined by the comparison function comparator.- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint

Discussion The new array contains references to the receivers elements, not copies of them. This method is similar to sortedArrayUsingFunction:context: (page 60), except that it uses the supplied hint to speed the sorting process. When you know the array is nearly sorted, this method is faster than sortedArrayUsingFunction:context:. If you sorted a large array (N entries) once, and you dont change it much (P additions and deletions, where P is much smaller than N), then you can reuse the work you did in the original sort by conceptually doing a merge sort between the N old items and the P new items. To obtain an appropriate hint, use sortedArrayHint (page 59). You should obtain this hint when the original array has been sorted, and keep hold of it until you need it, after the array has been modified. The hint is computed by sortedArrayHint (page 59) in O(N) (where N is the number of items). This assumes that items in the array implement a -hash method. Given a suitable hint, and assuming that the hash function is a good hash function, -sortedArrayUsingFunction:context:hint: (page 61) sorts the array in O(P*LOG(P)+N) where P is the number of adds or deletes. This is an improvement over the unhinted sort, O(N*LOG(N)), when P is small. The hint is simply an array of size N containing the N hashes. To re-sort you need internally to create a map table mapping a hash to the index. Using this map table on the new array, you can get a first guess for the indices, and then sort that. For example, a sorted array {A, B, D, E, F} with corresponding hash values {25, 96, 78, 32, 17}, may be subject to small changes that result in contents {E, A, C, B, F}. The mapping table maps the hashes {25, 96, 78, 32, 17} to the indices {#0, #1, #2, #3, #4}. If the hashes for {E, A, C, B, F} are {32, 25, 99, 96, 17}, then by using the mapping table you can get a first order sort {#3, #0, ?, #1, #4}, so therefore create an initial semi-sorted array {A, B, E, F}, and then perform a cheap merge sort with {C} that yields {A, B, C, E, F}.

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

61

CHAPTER 1

NSArray Class Reference

Availability Available in iPhone OS 2.0 and later. See Also sortedArrayUsingDescriptors: (page 60) sortedArrayUsingFunction:context: (page 60) sortedArrayUsingSelector: (page 62)

Declared InNSArray.h

sortedArrayUsingSelector:Returns an array that lists the receivers elements in ascending order, as determined by the comparison method specified by a given selector.- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

Parameterscomparator

A selector that identifies the method to use to compare two elements at a time. The method should return NSOrderedAscending if the receiver is smaller than the argument, NSOrderedDescending if the receiver is larger than the argument, and NSOrderedSame if they are equal. Return Value An array that lists the receivers elements in ascending order, as determined by the comparison method specified by the selector comparator. Discussion The new array contains references to the receivers 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: (page 966) 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:)];

Availability Available in iPhone OS 2.0 and later. See Also sortedArrayUsingDescriptors: (page 60) sortedArrayUsingFunction:context: (page 60) sortedArrayUsingFunction:context:hint: (page 61)

Related Sample Code TableViewSuite Declared InNSArray.h

62

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

subarrayWithRange:Returns a new array containing the receivers elements that fall within the limits specified by a given range.- (NSArray *)subarrayWithRange:(NSRange)range

Parametersrange

A range within the receivers range of elements. Return Value A new array containing the receivers elements that fall within the limits specified by range. Discussion If range isnt within the receivers 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];

Availability Available in iPhone OS 2.0 and later. Related Sample Code DrillDownSave Declared InNSArray.h

valueForKey:Returns an array containing the results of invoking valueForKey: using key on each of the receiver's objects.- (id)valueForKey:(NSString *)key

Discussion The returned array contains NSNull elements for each object that returns nil. Availability Available in iPhone OS 2.0 and later. See Also setValue:forKey: (page 59)

Declared InNSKeyValueCoding.h

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

63

CHAPTER 1

NSArray Class Reference

writeToFile:atomically:Writes the contents of the receiver to a file at a given path.- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Parameterspath

The path at which to write the contents of the receiver. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath (page 1018) 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, wont be corrupted even if the system should crash during writing. Return Value YES if the file is written successfully, otherwise NO. Discussion If the receivers contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: (page 38) or the instance method initWithContentsOfFile: (page 51). 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. Availability Available in iPhone OS 2.0 and later. See Also initWithContentsOfFile: (page 51)

Declared InNSArray.h

writeToURL:atomically:Writes the contents of the receiver to the location specified by a given URL.- (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag

ParametersaURL

The location at which to write the receiver.flag

If YES, the array is written to an auxiliary location, and then the auxiliary location is renamed to aURL. If NO, the array is written directly to aURL. The YES option guarantees that aURL, if it exists at all, wont be corrupted even if the system should crash during writing. Return Value YES if the location is written successfully, otherwise NO.

64

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 1

NSArray Class Reference

Discussion If the receivers contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the location written by this method can be used to initialize a new array with the class method arrayWithContentsOfURL: (page 39) or the instance method initWithContentsOfURL: (page 52). Availability Available in iPhone OS 2.0 and later. See Also initWithContentsOfURL: (page 52)

Declared InNSArray.h

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

65

CHAPTER 1

NSArray Class Reference

66

Instance Methods2008-06-27 | 1997, 2008 Apple Inc. All Rights Reserved.

CHAPTER 2

NSAssertionHandler Class Reference

Inherits from Conforms to Framework Availability Declared in Companion guide

NSObject NSObject (NSObject) /System/Library/Frameworks/Foundation.framework Available in iPhone OS 2.0 and later. Foundation/NSException.h Assertions and Logging

OverviewNSAssertionHandler objects are automatically created to handle false assertions. Assertion macros, such as NSAssert and NSCAssert, are used to evaluate a condition, and, if the condition evaluates to false, the macros pass a string to an NSAssertionHandler object describing the failure. Each thread has its own NSAssertionHandler object. When invoked, an assertion handler prints an error message that includes

the method and class (or function) containing the assertion and raises an NSInternalInconsistencyException. You create assertions only using the assertion macrosyou rarely need to invoke NSAssertionHandler methods directly. The macros for use inside methods and functions send handleFailureInMethod:object:file:lineNumber:description: (page 69) and handleFailureInFunction:file:lineNumber:description: (page 68) messages respectively to the current assertion handler. The assertion handler for the current thread is obtained using the currentHandler (page 68) class method. If you need to customize the behavior of NSAssertionHandler, create a subclass, overriding the above two methods, and install your instance into the current threads attributes dictionary with the key NSAssertionHandler.

TasksHandling Assertion Failures+ currentHandler (page 68) Returns