Foundation Framework ReferenceContents The Foundation Framework 26 Introduction 28 Classes 34 NSArray Class Reference 35 Overview 36 Adopted Protocols 37 Tasks 38 Class Methods 43 Instance Methods 49 Constants 96 NSAssertionHandler Class Reference 98 Overview 98 Tasks 99 Class Methods 99 Instance Methods 100 Constants 101 NSAttributedString Class Reference 102 Overview 102 Adopted Protocols 103 Tasks 103 Instance Methods 105 Constants 115 NSAutoreleasePool Class Reference 116 Overview 116 Tasks 119 Class Methods 119 Instance Methods 120 NSBlockOperation Class Reference 123 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 2Overview 123 Tasks 123 Class Methods 124 Instance Methods 124 NSBundle Class Reference 126 Overview 126 Tasks 127 Class Methods 132 Instance Methods 141 Constants 171 Notifications 173 NSCache Class Reference 174 Overview 174 Tasks 175 Instance Methods 176 NSCachedURLResponse Class Reference 185 Overview 185 Tasks 185 Instance Methods 186 Constants 189 NSCalendar Class Reference 191 Overview 191 Tasks 192 Class Methods 194 Instance Methods 195 Constants 209 NSCharacterSet Class Reference 213 Overview 213 Adopted Protocols 214 Tasks 214 Class Methods 216 Instance Methods 227 Constants 230 NSCoder Class Reference 231 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 3 ContentsOverview 231 Tasks 232 Instance Methods 235 NSComparisonPredicate Class Reference 257 Overview 257 Tasks 257 Class Methods 258 Instance Methods 260 Constants 263 NSCompoundPredicate Class Reference 269 Overview 269 Tasks 270 Class Methods 270 Instance Methods 272 Constants 273 NSCondition Class Reference 275 Overview 275 Tasks 276 Instance Methods 277 NSConditionLock Class Reference 281 Overview 281 Adopted Protocols 281 Tasks 282 Instance Methods 283 NSCountedSet Class Reference 289 Overview 289 Tasks 290 Instance Methods 291 NSData Class Reference 296 Overview 296 Adopted Protocols 297 Tasks 297 Class Methods 300 Instance Methods 307 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 4 ContentsConstants 321 NSDataDetector Class Reference 326 Overview 326 Tasks 328 Properties 329 Class Methods 329 Instance Methods 330 NSDate Class Reference 332 Overview 332 Tasks 334 Class Methods 336 Instance Methods 341 Constants 352 Notifications 352 NSDateComponents Class Reference 353 Overview 353 Tasks 354 Instance Methods 357 Constants 374 NSDateFormatter Class Reference 376 Overview 376 Tasks 378 Class Methods 383 Instance Methods 387 Constants 424 NSDecimalNumber Class Reference 427 Overview 427 Tasks 427 Class Methods 431 Instance Methods 437 Constants 448 NSDecimalNumberHandler Class Reference 450 Overview 450 Adopted Protocols 450 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 5 ContentsTasks 451 Class Methods 451 Instance Methods 453 NSDictionary Class Reference 455 Overview 455 Adopted Protocols 457 Tasks 457 Class Methods 462 Instance Methods 468 NSDirectoryEnumerator Class Reference 499 Overview 499 Tasks 499 Instance Methods 500 NSEnumerator Class Reference 503 Overview 503 Tasks 504 Instance Methods 504 NSError Class Reference 506 Overview 506 Adopted Protocols 507 Tasks 507 Class Methods 508 Instance Methods 509 Constants 515 NSException Class Reference 520 Overview 520 Adopted Protocols 520 Tasks 521 Class Methods 522 Instance Methods 524 NSExpression Class Reference 528 Overview 528 Tasks 530 Class Methods 532 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 6 ContentsInstance Methods 546 Constants 552 NSFileCoordinator Class Reference 555 Overview 555 Tasks 556 Class Methods 557 Instance Methods 559 Constants 569 NSFileHandle Class Reference 572 Overview 572 Tasks 573 Properties 576 Class Methods 577 Instance Methods 584 Constants 598 Notifications 599 NSFileManager Class Reference 602 Overview 602 Tasks 603 Class Methods 609 Instance Methods 609 Delegate Methods 667 Constants 670 NSFileWrapper Class Reference 681 Overview 681 Adopted Protocols 682 Tasks 682 Instance Methods 685 Constants 710 NSFormatter Class Reference 713 Overview 713 Tasks 714 Instance Methods 714 NSHTTPCookie Class Reference 722 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 7 ContentsOverview 722 Adopted Protocols 722 Tasks 723 Class Methods 724 Instance Methods 726 Constants 732 NSHTTPCookieStorage Class Reference 736 Overview 736 Tasks 736 Class Methods 738 Instance Methods 738 Constants 743 Notifications 744 NSHTTPURLResponse Class Reference 745 Overview 745 Adopted Protocols 745 Tasks 746 Class Methods 746 Instance Methods 747 NSIndexPath Class Reference 748 Overview 748 Adopted Protocols 749 Tasks 750 Class Methods 751 Instance Methods 752 NSIndexSet Class Reference 757 Overview 757 Adopted Protocols 758 Tasks 758 Class Methods 761 Instance Methods 762 NSInputStream Class Reference 781 Overview 781 Tasks 782 Class Methods 783 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 8 ContentsInstance Methods 785 NSInvocation Class Reference 789 Overview 789 Adopted Protocols 790 Tasks 790 Class Methods 791 Instance Methods 792 NSInvocationOperation Class Reference 800 Overview 800 Tasks 800 Instance Methods 801 Constants 803 NSKeyedArchiver Class Reference 805 Overview 805 Tasks 806 Class Methods 808 Instance Methods 810 Constants 819 NSKeyedUnarchiver Class Reference 820 Overview 820 Tasks 821 Class Methods 823 Instance Methods 825 Constants 834 NSLinguisticTagger Class Reference 835 Overview 835 Tasks 835 Class Methods 837 Instance Methods 837 Constants 845 NSLocale Class Reference 854 Overview 854 Tasks 855 Class Methods 857 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 9 ContentsInstance Methods 866 Constants 870 Notifications 876 NSLock Class Reference 878 Overview 878 Adopted Protocols 878 Tasks 879 Instance Methods 879 NSMachPort Class Reference 882 Overview 882 Tasks 883 Class Methods 884 Instance Methods 885 Constants 889 NSMessagePort Class Reference 890 Overview 890 NSMetadataItem Class Reference 891 Overview 891 Adopted Protocols 891 Tasks 891 Instance Methods 892 Constants 893 NSMetadataQuery Class Reference 897 Overview 897 Tasks 898 Instance Methods 900 Constants 914 Notifications 915 NSMetadataQueryAttributeValueTuple Class Reference 917 Overview 917 Tasks 917 Instance Methods 918 NSMetadataQueryResultGroup Class Reference 920 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 10 ContentsOverview 920 Tasks 920 Instance Methods 921 NSMethodSignature Class Reference 924 Overview 924 Tasks 925 Class Methods 926 Instance Methods 926 NSMutableArray Class Reference 930 Overview 930 Tasks 931 Class Methods 934 Instance Methods 935 NSMutableAttributedString Class Reference 956 Overview 956 Tasks 957 Instance Methods 958 NSMutableCharacterSet Class Reference 967 Overview 967 Tasks 968 Instance Methods 968 NSMutableData Class Reference 973 Overview 973 Tasks 974 Class Methods 975 Instance Methods 976 NSMutableDictionary Class Reference 984 Overview 984 Tasks 985 Class Methods 986 Instance Methods 987 NSMutableIndexSet Class Reference 993 Overview 993 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 11 ContentsTasks 993 Instance Methods 994 NSMutableOrderedSet Class Reference 999 Overview 999 Tasks 999 Class Methods 1002 Instance Methods 1002 NSMutableSet Class Reference 1018 Overview 1018 Tasks 1019 Class Methods 1020 Instance Methods 1021 NSMutableString Class Reference 1027 Overview 1027 Tasks 1028 Class Methods 1029 Instance Methods 1029 NSMutableURLRequest Class Reference 1035 Overview 1035 Tasks 1036 Instance Methods 1037 NSNetService Class Reference 1044 Overview 1044 Tasks 1045 Class Methods 1047 Instance Methods 1048 Constants 1061 NSNetServiceBrowser Class Reference 1064 Overview 1064 Tasks 1065 Instance Methods 1066 NSNotification Class Reference 1072 Overview 1072 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 12 ContentsAdopted Protocols 1073 Tasks 1073 Class Methods 1074 Instance Methods 1075 NSNotificationCenter Class Reference 1078 Overview 1078 Tasks 1080 Class Methods 1081 Instance Methods 1082 NSNotificationQueue Class Reference 1089 Overview 1089 Tasks 1089 Class Methods 1090 Instance Methods 1091 Constants 1093 NSNull Class Reference 1096 Overview 1096 Adopted Protocols 1096 Tasks 1097 Class Methods 1097 NSNumber Class Reference 1098 Overview 1098 Tasks 1099 Class Methods 1103 Instance Methods 1110 NSNumberFormatter Class Reference 1127 Overview 1127 Tasks 1128 Class Methods 1137 Instance Methods 1138 Constants 1193 NSObject Class Reference 1198 Overview 1198 Tasks 1199 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 13 ContentsClass Methods 1203 Instance Methods 1219 NSOperation Class Reference 1243 Overview 1243 Tasks 1250 Instance Methods 1252 Constants 1264 NSOperationQueue Class Reference 1266 Overview 1266 Tasks 1268 Class Methods 1270 Instance Methods 1271 Constants 1278 NSOrderedSet Class Reference 1279 Overview 1279 Tasks 1280 Class Methods 1284 Instance Methods 1291 NSOrthography Class Reference 1324 Overview 1324 Tasks 1325 Properties 1326 Class Methods 1328 Instance Methods 1328 NSOutputStream Class Reference 1331 Overview 1331 Tasks 1332 Class Methods 1333 Instance Methods 1336 NSPipe Class Reference 1341 Overview 1341 Tasks 1341 Class Methods 1342 Instance Methods 1342 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 14 ContentsNSPort Class Reference 1345 Overview 1345 Adopted Protocols 1346 Tasks 1346 Class Methods 1348 Instance Methods 1349 Notifications 1354 NSPredicate Class Reference 1355 Overview 1355 Tasks 1356 Class Methods 1357 Instance Methods 1360 NSProcessInfo Class Reference 1364 Overview 1364 Tasks 1366 Class Methods 1367 Instance Methods 1368 Constants 1374 NSPropertyListSerialization Class Reference 1376 Overview 1376 Tasks 1376 Class Methods 1377 Constants 1383 NSProxy Class Reference 1386 Overview 1386 Adopted Protocols 1387 Tasks 1387 Class Methods 1389 Instance Methods 1390 NSRecursiveLock Class Reference 1394 Overview 1394 Adopted Protocols 1394 Tasks 1395 Instance Methods 1395 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 15 ContentsNSRegularExpression Class Reference 1398 Overview 1398 Tasks 1408 Properties 1410 Class Methods 1411 Instance Methods 1413 Constants 1422 NSRunLoop Class Reference 1427 Overview 1427 Tasks 1428 Class Methods 1429 Instance Methods 1430 Constants 1440 NSScanner Class Reference 1441 Overview 1441 Tasks 1442 Class Methods 1444 Instance Methods 1445 NSSet Class Reference 1461 Overview 1461 Adopted Protocols 1462 Tasks 1463 Class Methods 1466 Instance Methods 1471 NSSortDescriptor Class Reference 1493 Overview 1493 Adopted Protocols 1494 Tasks 1494 Class Methods 1496 Instance Methods 1498 NSStream Class Reference 1504 Overview 1504 Tasks 1506 Instance Methods 1507 Constants 1513 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 16 ContentsNSString Class Reference 1521 Overview 1521 Adopted Protocols 1524 Tasks 1525 Class Methods 1538 Instance Methods 1552 Constants 1649 NSTextCheckingResult Class Reference 1661 Overview 1661 Tasks 1661 Properties 1665 Class Methods 1670 Instance Methods 1679 Constants 1680 NSThread Class Reference 1685 Overview 1685 Tasks 1686 Class Methods 1688 Instance Methods 1695 Notifications 1703 NSTimer Class Reference 1705 Overview 1705 Tasks 1707 Class Methods 1708 Instance Methods 1712 NSTimeZone Class Reference 1718 Overview 1718 Tasks 1719 Class Methods 1721 Instance Methods 1729 Constants 1737 Notifications 1739 NSUbiquitousKeyValueStore Class Reference 1740 Overview 1740 Tasks 1741 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 17 ContentsClass Methods 1743 Instance Methods 1744 Constants 1754 Notifications 1756 NSUndoManager Class Reference 1757 Overview 1757 Tasks 1758 Instance Methods 1761 Constants 1779 Notifications 1780 NSURL Class Reference 1784 Overview 1784 Adopted Protocols 1787 Tasks 1787 Class Methods 1791 Instance Methods 1799 Constants 1823 NSURLAuthenticationChallenge Class Reference 1841 Overview 1841 Tasks 1841 Instance Methods 1842 NSURLCache Class Reference 1846 Overview 1846 Tasks 1846 Class Methods 1848 Instance Methods 1849 NSURLConnection Class Reference 1855 Overview 1855 Tasks 1856 Class Methods 1857 Instance Methods 1860 NSURLCredential Class Reference 1866 Overview 1866 Adopted Protocols 1866 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 18 ContentsTasks 1866 Class Methods 1868 Instance Methods 1870 Constants 1874 NSURLCredentialStorage Class Reference 1876 Overview 1876 Tasks 1876 Class Methods 1877 Instance Methods 1877 Notifications 1881 NSURLProtectionSpace Class Reference 1882 Overview 1882 Adopted Protocols 1882 Tasks 1882 Instance Methods 1883 Constants 1889 NSURLProtocol Class Reference 1893 Overview 1893 Tasks 1894 Class Methods 1895 Instance Methods 1901 NSURLRequest Class Reference 1904 Overview 1904 Adopted Protocols 1905 Tasks 1905 Class Methods 1906 Instance Methods 1908 Constants 1914 NSURLResponse Class Reference 1917 Overview 1917 Adopted Protocols 1918 Tasks 1918 Instance Methods 1919 Constants 1922 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 19 ContentsNSUserDefaults Class Reference 1923 Overview 1923 Tasks 1925 Class Methods 1928 Instance Methods 1930 Constants 1951 Notifications 1952 NSValue Class Reference 1953 Overview 1953 Adopted Protocols 1953 Tasks 1954 Class Methods 1955 Instance Methods 1958 NSValueTransformer Class Reference 1962 Overview 1962 Tasks 1963 Class Methods 1964 Instance Methods 1966 Constants 1968 NSXMLParser Class Reference 1970 Overview 1970 Tasks 1971 Instance Methods 1973 Constants 1982 Protocols 1997 NSCoding Protocol Reference 1998 Overview 1998 Tasks 1999 Instance Methods 1999 NSCopying Protocol Reference 2001 Overview 2001 Tasks 2002 Instance Methods 2002 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 20 ContentsNSDecimalNumberBehaviors Protocol Reference 2003 Overview 2003 Tasks 2003 Instance Methods 2004 Constants 2006 NSErrorRecoveryAttempting Protocol Reference 2009 Overview 2009 Tasks 2009 Instance Methods 2010 NSFastEnumeration Protocol Reference 2012 Overview 2012 Tasks 2012 Instance Methods 2013 Constants 2013 NSFileManagerDelegate Protocol Reference 2015 Overview 2015 Tasks 2015 Instance Methods 2017 NSFilePresenter Protocol Reference 2033 Overview 2033 Tasks 2034 Properties 2035 Instance Methods 2036 NSKeyedArchiverDelegate Protocol Reference 2049 Overview 2049 Tasks 2049 Instance Methods 2050 NSKeyedUnarchiverDelegate Protocol Reference 2053 Overview 2053 Tasks 2053 Instance Methods 2054 NSKeyValueCoding Protocol Reference 2058 Overview 2058 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 21 ContentsTasks 2058 Class Methods 2060 Instance Methods 2061 Constants 2072 NSKeyValueObserving Protocol Reference 2076 Overview 2076 Tasks 2076 Class Methods 2078 Instance Methods 2079 Constants 2088 NSLocking Protocol Reference 2095 Overview 2095 Tasks 2095 Instance Methods 2096 NSMachPortDelegate Protocol Reference 2097 Overview 2097 Tasks 2097 Instance Methods 2097 NSMetadataQueryDelegate Protocol Reference 2099 Overview 2099 Tasks 2099 Instance Methods 2099 NSMutableCopying Protocol Reference 2102 Overview 2102 Tasks 2102 Instance Methods 2103 NSNetServiceBrowserDelegate Protocol Reference 2104 Overview 2104 Tasks 2104 Instance Methods 2105 NSNetServiceDelegate Protocol Reference 2110 Overview 2110 Tasks 2110 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 22 ContentsInstance Methods 2111 NSObject Protocol Reference 2116 Overview 2116 Tasks 2117 Instance Methods 2119 NSPortDelegate Protocol Reference 2134 Overview 2134 Tasks 2134 Instance Methods 2134 NSStreamDelegate Protocol Reference 2136 Overview 2136 Tasks 2136 Instance Methods 2137 NSURLAuthenticationChallengeSender Protocol Reference 2138 Overview 2138 Tasks 2138 Instance Methods 2139 NSURLConnectionDelegate Protocol Reference 2141 Overview 2141 Tasks 2142 Instance Methods 2142 NSURLProtocolClient Protocol Reference 2148 Overview 2148 Tasks 2148 Instance Methods 2149 NSXMLParserDelegate Protocol Reference 2154 Overview 2154 Tasks 2154 Instance Methods 2156 Functions 2170 Foundation Functions Reference 2171 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 23 ContentsOverview 2171 Functions by Task 2171 Functions 2180 Data Types 2257 Foundation Data Types Reference 2258 Overview 2258 Data Types 2258 Constants 2265 Foundation Constants Reference 2266 Overview 2266 Constants 2266 Document Revision History 2302 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 24 ContentsFigures and Tables The Foundation Framework 26 Figure I-1 Cocoa Objective-C Hierarchy for Foundation 30 NSIndexPath Class Reference 748 Figure 38-1 Index path 1.4.3.2 749 NSNotificationCenter Class Reference 1078 Table 68-1 Types of dispatch table entries 1079 Table 68-2 Example notification dispatch table 1079 NSOperation Class Reference 1243 Table 74-1 Key paths for operation object states 1248 NSRegularExpression Class Reference 1398 Table 86-1 Regular Expression Metacharacters 1402 Table 86-2 Regular Expression Operators 1404 Table 86-3 Template Matching Format 1406 Table 86-4 Flag Options 1407 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 25Framework /System/Library/Frameworks/Foundation.framework Header file directories /System/Library/Frameworks/Foundation.framework/Headers Declared in FoundationErrors.h NSArray.h NSAttributedString.h NSAutoreleasePool.h NSBundle.h NSByteOrder.h NSCache.h NSCalendar.h NSCharacterSet.h NSCoder.h NSComparisonPredicate.h NSCompoundPredicate.h NSData.h NSDate.h NSDateFormatter.h NSDecimal.h NSDecimalNumber.h NSDictionary.h NSEnumerator.h NSError.h NSException.h NSExpression.h NSFileCoordinator.h NSFileHandle.h NSFileManager.h NSFilePresenter.h NSFileWrapper.h NSFormatter.h NSHTTPCookie.h 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 26NSHTTPCookieStorage.h NSIndexPath.h NSIndexSet.h NSInvocation.h NSKeyValueCoding.h NSKeyValueObserving.h NSKeyedArchiver.h NSLinguisticTagger.h NSLocale.h NSLock.h NSMetadata.h NSMethodSignature.h NSNetServices.h NSNotification.h NSNotificationQueue.h NSNull.h NSNumberFormatter.h NSObjCRuntime.h NSObject.h NSOperation.h NSOrderedSet.h NSOrthography.h NSPathUtilities.h NSPort.h NSPredicate.h NSProcessInfo.h NSPropertyList.h NSProxy.h NSRange.h NSRegularExpression.h NSRunLoop.h NSScanner.h NSSet.h NSSortDescriptor.h NSStream.h NSString.h NSTextCheckingResult.h 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 27NSThread.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 NSUbiquitousKeyValueStore.h NSUndoManager.h NSUserDefaults.h NSValue.h NSValueTransformer.h NSXMLParser.h NSZone.h Introduction The 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. Introduction 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 28The 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 30) for a list of those classes that make up 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 Classes The Foundation class hierarchy is rooted in the Foundation framework’s NSObject class (see Figure I-1 (page 30)). 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 clusters—abstract 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. Introduction 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 29Note In the following class-hierarchy diagrams, blue-shaded areas include classes that are available in Mac OS X and iOS; gray-shaded areas include classes that are available in Mac OS X only. Figure I-1 Cocoa Objective-C Hierarchy for Foundation Value Objects NSValue NSNumber NSDate NSDateComponents NSCalendarDate NSDecimalNumberHandler NSLocale NSDecimalNumber NSTimeZone NSData NSMutableData NSPurgeableData NSNull Collections NSEnumerator NSDirectoryEnumerator NSSet NSMutableSet NSCountedSet NSDictionary NSMutableDictionary NSArray NSMutableArray Strings NSFormatter NSDateFormatter NSNumberFormatter NSMutableStringNSString NSScanner NSObject NSValueTransformer NSAffineTransform NSCalendar NSCache NSSortDescriptor NSIndexSet NSIndexPath NSMutableIndexSet XML NSXMLDocument NSXMLDTD NSXMLDTDNode NSXMLElement NSExpression NSComparisonPredicate NSCompoundPredicate Predicates NSPredicate NSMutableCharacterSetNSCharacterSet NSXMLNode NSXMLParser NSMutableAttributedStringNSAttributedString NSHashTable NSMapTable NSPointerArray NSPointerFunctions Introduction 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 30Objective-C Foundation Continued Operating-System Services Interprocess Communication NSHost NSNetService NSNetServiceBrowser NSOrthography NSProcessInfo NSRunLoop File System NSBundle NSFileHandle NSFileManager NSPort NSMachPort NSMessagePort NSSocketPort NSPipe NSTextCheckingResult NSTimer NSUserDefaults URL NSCachedURLResponse NSHTTPCookie Locking/Threading NSConditionLock NSDistributedLock NSLock NSOperation NSOperationQueue NSRecursiveLock NSTask NSThread NSHTTPCookieStorage NSURL NSURLAuthorizationChallenge NSURLCache NSURLConnection NSURLProtocol NSURLRequest NSURLResponse NSURLCredential NSURLCredentialStorage NSURLDownload NSURLProtectionSpace NSObject NSError NSMutableURLRequest NSHTTPURLResponse NSBlockOperation NSInvocationOperation NSStream NSInputStream NSOutputStream NSSpellServer NSMetadataItem NSMetadataQuery NSMetadataQueryAttributeValueTuple NSMetadataQueryResultGroup NSPortNameServer NSMachBootstrapServer NSMessagePortNameServer NSSocketPortNameServer NSPortMessage Introduction 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 31NSProxy Notifications NSNotification NSNotificationCenter NSNotificationQueue NSDistributedNotificationCenter Archiving and Serialization NSCoder NSPropertyListSerialization NSArchiver NSKeyedArchiver NSKeyedUnarchiver NSUnarchiver Objective-C Language Services NSMethodSignature NSInvocation NSException NSClassDescription NSAutoreleasePool NSAssertionHandler Scripting NSScriptClassDescription NSAppleScript NSScriptObjectSpecifier NSScriptCommandDescription NSPositionalSpecifier NSScriptCoercionHandler NSScriptCommand NSCloneCommand NSCloseCommand NSCountCommand NSCreateCommand NSDeleteCommand NSExistsCommand NSGetCommand NSMoveCommand NSQuitCommand NSSetCommand NSScriptExecutionContext NSScriptSuiteRegistry NSIndexSpecifier NSMiddleSpecifier NSNameSpecifier NSPropertySpecifier NSRandomSpecifier NSRangeSpecifier NSRelativeSpecifier NSUniqueIDSpecifier NSWhoseSpecifier NSScriptWhoseTest NSLogicalTest NSSpecifierTest NSAppleEventManager NSAppleEventDescriptor NSObject Objective-C Foundation Continued NSPortCoder NSUndoManager NSGarbageCollector Distributed Objects NSDistantObjectRequest NSConnection 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. Introduction 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 32 ● 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. ● 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. Introduction 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 33 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 34 ClassesInherits from NSObject Conforms to NSCoding NSCopying NSMutableCopying NSFastEnumeration NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSArray.h Foundation/NSKeyValueCoding.h Foundation/NSKeyValueObserving.h Foundation/NSPathUtilities.h Foundation/NSPredicate.h Foundation/NSSortDescriptor.h Companion guides Collections Programming Topics Key-Value Coding Programming Guide Property List Programming Guide Predicate Programming Guide Related sample code Birthdays DrillDownSave iPhoneCoreDataRecipes TableViewSuite TheElements 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 35 NSArray Class ReferenceOverview NSArray and its subclass NSMutableArray manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef. See “Toll-Free Bridging” for more information on toll-free bridging. Subclassing Notes There is typically little reason to subclass NSArray. The class does well what it is designed to do—maintain 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. ● Acquiring more information about what is happening to the collection (for example, statistics gathering). Methods to Override Any subclass of NSArray must override the primitive instance methods count (page 53) and objectAtIndex: (page 81). 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 1229) 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. NSArray Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 36Special Considerations In most cases your custom NSArray class should conform to Cocoa’s object-ownership conventions. Thus you must send retain (page 2130) to each object that you add to your collection and release (page 2128) 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 Subclassing Before making a custom class of NSArray, investigate NSPointerArray 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. Alternatively, you could use composition to achieve the desired behavior. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSMutableCopying mutableCopyWithZone: (page 2103) NSFastEnumeration countByEnumeratingWithState:objects:count: (page 2013) NSArray Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 37Tasks Creating an Array + array (page 43) Creates and returns an empty array. + arrayWithArray: (page 44) Creates and returns an array containing the objects in another given array. + arrayWithContentsOfFile: (page 45) Creates and returns an array containing the contents of the file specified by a given path. + arrayWithContentsOfURL: (page 45) Creates and returns an array containing the contents specified by a given URL. + arrayWithObject: (page 46) Creates and returns an array containing a given object. + arrayWithObjects: (page 47) Creates and returns an array containing the objects in the argument list. + arrayWithObjects:count: (page 48) Creates and returns an array that includes a given number of objects from a given C array. Initializing an Array – initWithArray: (page 74) Initializes a newly allocated array by placing in it the objects contained in a given array. – initWithArray:copyItems: (page 74) Initializes a newly allocated array using anArray as the source of data objects for the array. – initWithContentsOfFile: (page 75) Initializes a newly allocated array with the contents of the file specified by a given path. – initWithContentsOfURL: (page 76) Initializes a newly allocated array with the contents of the location specified by a given URL. – initWithObjects: (page 77) Initializes a newly allocated array by placing in it the objects in the argument list. – initWithObjects:count: (page 77) Initializes a newly allocated array to include a given number of objects from a given C array. NSArray Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 38Querying an Array – containsObject: (page 52) Returns a Boolean value that indicates whether a given object is present in the array. – count (page 53) Returns the number of objects currently in the array. – getObjects:range: (page 61) Copies the objects contained in the array that fall within the specified range to aBuffer. – lastObject (page 79) Returns the object in the array with the highest index value. – objectAtIndex: (page 81) Returns the object located at index. – objectsAtIndexes: (page 82) Returns an array containing the objects in the array at the indexes specified by a given index set. – objectEnumerator (page 81) Returns an enumerator object that lets you access each object in the array. – reverseObjectEnumerator (page 86) Returns an enumerator object that lets you access each object in the array, in reverse order. – getObjects: (page 60) Deprecated in iOS 4.0 Copies all the objects contained in the array to aBuffer. (Deprecated. Use getObjects:range: (page 61) instead.) Finding Objects in an Array – indexOfObject: (page 65) Returns the lowest index whose corresponding array value is equal to a given object. – indexOfObject:inRange: (page 66) Returns the lowest index within a specified range whose corresponding array value is equal to a given object . – indexOfObjectIdenticalTo: (page 70) Returns the lowest index whose corresponding array value is identical to a given object. – indexOfObjectIdenticalTo:inRange: (page 70) Returns the lowest index within a specified range whose corresponding array value is equal to a given object . NSArray Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 39– indexOfObjectPassingTest: (page 71) Returns the index of the first object in the array that passes a test in a given Block. – indexOfObjectWithOptions:passingTest: (page 72) Returns the index of an object in the array that passes a test in a given Block for a given set of enumeration options. – indexOfObjectAtIndexes:options:passingTest: (page 69) Returns the index, from a given set of indexes, of the first object in the array that passes a test in a given Block for a given set of enumeration options. – indexesOfObjectsPassingTest: (page 64) Returns the indexes of objects in the array that pass a test in a given Block. – indexesOfObjectsWithOptions:passingTest: (page 64) Returns the indexes of objects in the array that pass a test in a given Block for a given set of enumeration options. – indexesOfObjectsAtIndexes:options:passingTest: (page 62) Returns the indexes, from a given set of indexes, of objects in the array that pass a test in a given Block for a given set of enumeration options. – indexOfObject:inSortedRange:options:usingComparator: (page 67) Returns the index, within a specified range, of an object compared with elements in the array using a given NSComparator block. Sending Messages to Elements – makeObjectsPerformSelector: (page 79) 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. – makeObjectsPerformSelector:withObject: (page 80) Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object. – enumerateObjectsUsingBlock: (page 57) Executes a given block using each object in the array, starting with the first object and continuing through the array to the last object. – enumerateObjectsWithOptions:usingBlock: (page 58) Executes a given block using each object in the array. – enumerateObjectsAtIndexes:options:usingBlock: (page 56) Executes a given block using the objects in the array at the specified indexes. NSArray Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 40Comparing Arrays – firstObjectCommonWithArray: (page 59) Returns the first object contained in the receiving array that’s equal to an object in another given array. – isEqualToArray: (page 78) Compares the receiving array to another array. Deriving New Arrays – arrayByAddingObject: (page 51) Returns a new array that is a copy of the receiving array with a given object added to the end. – arrayByAddingObjectsFromArray: (page 51) Returns a new array that is a copy of the receiving array with the objects contained in another array added to the end. – filteredArrayUsingPredicate: (page 59) 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. – subarrayWithRange: (page 93) Returns a new array containing the receiving array’s elements that fall within the limits specified by a given range. Sorting – sortedArrayHint (page 87) Analyzes the array and returns a “hint” that speeds the sorting of the array when the hint is supplied to sortedArrayUsingFunction:context:hint: (page 90). – sortedArrayUsingFunction:context: (page 89) Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator. – sortedArrayUsingFunction:context:hint: (page 90) Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator. – sortedArrayUsingDescriptors: (page 88) Returns a copy of the receiving array sorted as specified by a given array of sort descriptors. NSArray Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 41– sortedArrayUsingSelector: (page 91) Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given selector. – sortedArrayUsingComparator: (page 88) 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. – sortedArrayWithOptions:usingComparator: (page 92) 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. Working with String Elements – componentsJoinedByString: (page 52) Constructs and returns an NSString object that is the result of interposing a given separator between the elements of the array. Creating a Description – description (page 54) Returns a string that represents the contents of the array, formatted as a property list. – descriptionWithLocale: (page 54) Returns a string that represents the contents of the array, formatted as a property list. – descriptionWithLocale:indent: (page 55) Returns a string that represents the contents of the array, formatted as a property list. – writeToFile:atomically: (page 95) Writes the contents of the array to a file at a given path. – writeToURL:atomically: (page 95) Writes the contents of the array to the location specified by a given URL. Collecting Paths – pathsMatchingExtensions: (page 83) Returns an array containing all the pathname elements in the receiving array that have filename extensions from a given array. NSArray Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 42Key-Value Observing – addObserver:forKeyPath:options:context: (page 49) Raises an exception. – removeObserver:forKeyPath: (page 84) Raises an exception. – removeObserver:forKeyPath:context (page 84) Raises an exception. – removeObserver:fromObjectsAtIndexes:forKeyPath:context: (page 86) Raises an exception. – addObserver:toObjectsAtIndexes:forKeyPath:options:context: (page 50) Registers an observer to receive key value observer notifications for the specified key-path relative to the objects at the indexes. – removeObserver:fromObjectsAtIndexes:forKeyPath: (page 85) Removes anObserver from all key value observer notifications associated with the specified keyPath relative to the array’s objects at indexes. Key-Value Coding – setValue:forKey: (page 87) Invokes setValue:forKey: on each of the array's items using the specified value and key. – valueForKey: (page 94) Returns an array containing the results of invoking valueForKey: using key on each of the array's objects. Class Methods array Creates and returns an empty array. + (id)array Return Value An empty array. NSArray Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 43Discussion This method is used by mutable subclasses of NSArray. Availability Available in iOS 2.0 and later. See Also + arrayWithObject: (page 46) + arrayWithObjects: (page 47) Related Sample Code LazyTableImages LocateMe SeismicXML TheElements XMLPerformance Declared in NSArray.h 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. Availability Available in iOS 2.0 and later. See Also + arrayWithObjects: (page 47) – initWithObjects: (page 77) Declared in NSArray.h NSArray Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 44arrayWithContentsOfFile: 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: (page 95) 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 (NSString, NSData, NSDate, NSNumber, NSArray, 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. Availability Available in iOS 2.0 and later. See Also – writeToFile:atomically: (page 95) Related Sample Code Accessory GLPaint International Mountains QuickContacts TouchCells Declared in NSArray.h arrayWithContentsOfURL: Creates and returns an array containing the contents specified by a given URL. + (id)arrayWithContentsOfURL:(NSURL *)aURL NSArray Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 45Parameters aURL The location of a file containing a string representation of an array produced by the writeToURL:atomically: (page 95) method. Return Value An array containing the contents specified by aURL. Returns nil if the location can’t be opened or if the contents of the location can’t 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). The objects contained by this array are immutable, even if the array is mutable. Availability Available in iOS 2.0 and later. See Also – writeToURL:atomically: (page 95) Declared in NSArray.h arrayWithObject: Creates and returns an array containing a given object. + (id)arrayWithObject:(id)anObject Parameters anObject An object. Return Value An array containing the single element anObject. Availability Available in iOS 2.0 and later. See Also + array (page 43) + arrayWithObjects: (page 47) NSArray Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 46Related Sample Code CoreDataBooks iPhoneCoreDataRecipes ListAdder TaggedLocations TheElements Declared in NSArray.h 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. 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 iOS 2.0 and later. See Also + array (page 43) + arrayWithObject: (page 46) Related Sample Code GLPaint NSArray Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 47LazyTableImages ListAdder PVRTextureLoader QuickContacts Declared in NSArray.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 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" } Availability Available in iOS 2.0 and later. NSArray Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 48See Also – getObjects:range: (page 61) Declared in NSArray.h Instance Methods addObserver:forKeyPath:options:context: Raises an exception. - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context Parameters observer The object to register for KVO notifications. The observer must implement the key-value observing method observeValueForKeyPath:ofObject:change:context: (page 2083). keyPath The key path, relative to the array, of the property to observe. This value must not be nil. options A combination of NSKeyValueObservingOptions (page 2089) values that specifies what is included in observation notifications. context Arbitrary data that is passed to observer in observeValueForKeyPath:ofObject:change:context: (page 2083). Special Considerations NSArray 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 iOS 2.0 and later. See Also – removeObserver:forKeyPath: (page 84) – addObserver:toObjectsAtIndexes:forKeyPath:options:context: (page 50) NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 49Declared in NSKeyValueObserving.h addObserver:toObjectsAtIndexes:forKeyPath:options:context: Registers an observer to receive key value observer notifications for the specified key-path relative to the objects at the indexes. - (void)addObserver:(NSObject *)anObserver toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context Parameters anObserver The observer. indexes The index set. keyPath The key path, relative to the array, to be observed. options The options to be included in the notification. context The context passed to the notifications. 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 2079). Availability Available in iOS 2.0 and later. See Also – removeObserver:fromObjectsAtIndexes:forKeyPath: (page 85) Declared in NSKeyValueObserving.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 50arrayByAddingObject: 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. Availability Available in iOS 2.0 and later. See Also addObject: (page 935) (NSMutableArray) Declared in NSArray.h 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. Availability Available in iOS 2.0 and later. See Also addObjectsFromArray: (page 935) (NSMutableArray) NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 51Declared in NSArray.h 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. Availability Available in iOS 2.0 and later. See Also componentsSeparatedByString: (page 1562) (NSString) Declared in NSArray.h containsObject: Returns a Boolean value that indicates whether a given object is present in the array. - (BOOL)containsObject:(id)anObject NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 52Parameters 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: (page 2122) message to each of the array’s objects (and passing anObject as the parameter to each isEqual: message). Availability Available in iOS 2.0 and later. See Also – indexOfObject: (page 65) – indexOfObjectIdenticalTo: (page 70) Related Sample Code PVRTextureLoader Declared in NSArray.h count Returns the number of objects currently in the array. - (NSUInteger)count Return Value The number of objects currently in the array. Availability Available in iOS 2.0 and later. See Also – objectAtIndex: (page 81) Related Sample Code LocateMe SpeakHere TableViewSuite TheElements WeatherMap NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 53Declared in NSArray.h description Returns a string that represents the contents of the array, formatted as a property list. - (NSString *)description Return Value A string that represents the contents of the array, formatted as a property list. Availability Available in iOS 2.0 and later. See Also – descriptionWithLocale: (page 54) – descriptionWithLocale:indent: (page 55) Declared in NSArray.h descriptionWithLocale: Returns a string that represents the contents of the array, formatted as a property list. - (NSString *)descriptionWithLocale:(id)locale Parameters locale An NSLocale object or an NSDictionary object that specifies options used for formatting each of the array’s elements (where recognized). Specify nil if you don’t want the elements formatted. Return Value A string that represents the contents of the array, 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 55). Availability Available in iOS 2.0 and later. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 54See Also – description (page 54) – descriptionWithLocale:indent: (page 55) Declared in NSArray.h descriptionWithLocale:indent: Returns a string that represents the contents of the array, formatted as a property list. - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level Parameters locale An NSLocale object or an NSDictionary object that specifies options used for formatting each of the array’s elements (where recognized). Specify nil if you don’t 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 array, formatted as a property list. Discussion The returned NSString object contains the string representations of each of the array’s 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 element’s string representation. ● If the element responds to descriptionWithLocale: (page 54), that method is invoked to obtain the element’s string representation. ● If none of the above conditions is met, the element’s string representation is obtained by invoking its description (page 54) method. Availability Available in iOS 2.0 and later. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 55See Also – description (page 54) – descriptionWithLocale: (page 54) Declared in NSArray.h enumerateObjectsAtIndexes:options:usingBlock: Executes a given block using the objects in the array at the specified indexes. - (void)enumerateObjectsAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block Parameters indexSet The indexes of the objects over which to enumerate. 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 element specified by indexSet. You can specify NSEnumerationConcurrent and/or NSEnumerationReverse as enumeration options to modify this behavior. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 56Important If the Block parameter or the indexSet is nil this method will raise an exception. Availability Available in iOS 4.0 and later. See Also – enumerateObjectsUsingBlock: (page 57) – makeObjectsPerformSelector: (page 79) – makeObjectsPerformSelector:withObject: (page 80) Declared in NSArray.h enumerateObjectsUsingBlock: Executes a given block using each object in the array, starting with the first object and continuing through the array to the last object. - (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block Parameters 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 If the Block parameter is nil this method will raise an exception. Availability Available in iOS 4.0 and later. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 57See Also – enumerateObjectsWithOptions:usingBlock: (page 58) – makeObjectsPerformSelector: (page 79) – makeObjectsPerformSelector:withObject: (page 80) Declared in NSArray.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/or NSEnumerationReverse as enumeration options to modify this behavior. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 58Important If the Block parameter is nil this method will raise an exception. Availability Available in iOS 4.0 and later. See Also – enumerateObjectsUsingBlock: (page 57) – makeObjectsPerformSelector: (page 79) – makeObjectsPerformSelector:withObject: (page 80) Declared in NSArray.h 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. Discussion For more details, see Predicate Programming Guide. Availability Available in iOS 3.0 and later. Declared in NSPredicate.h firstObjectCommonWithArray: Returns the first object contained in the receiving array that’s equal to an object in another given array. - (id)firstObjectCommonWithArray:(NSArray *)otherArray NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 59Parameters otherArray An array. Return Value Returns the first object contained in the receiving array that’s equal to an object in otherArray. If no such object is found, returns nil. Discussion This method uses isEqual: (page 2122) to check for object equality. Availability Available in iOS 2.0 and later. See Also – containsObject: (page 52) Declared in NSArray.h getObjects: Copies all the objects contained in the array to aBuffer. (Deprecated in iOS 4.0. Use getObjects:range: (page 61) instead.) - (void)getObjects:(id *)aBuffer Parameters aBuffer A C array of objects of size at least the count of the array. Discussion The method copies into aBuffer all the objects in the array; the size of the buffer must therefore be at least the count of the array multiplied by the size of an object reference, as shown in the following example (note that this is just an example, you should typically not create a buffer simply to iterate over the contents of an array): NSArray *mArray = // ...; id *objects; NSUInteger count = [mArray count]; NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 60objects = malloc(sizeof(id) * count); [mArray getObjects:objects]; for (i = 0; i < count; i++) { NSLog(@"object at index %d: %@", i, objects[i]); } free(objects); Special Considerations This deprecated method is unsafe because it could potentially cause buffer overruns. Availability Available in iOS 2.0 and later. Deprecated in iOS 4.0. See Also + arrayWithObjects:count: (page 48) Declared in NSArray.h 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 (page 2292). NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 61Discussion 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); Availability Available in iOS 2.0 and later. See Also + arrayWithObjects:count: (page 48) Declared in NSArray.h indexesOfObjectsAtIndexes:options:passingTest: Returns the indexes, from a given set of indexes, of objects in the array that pass a test in a given Block for a given set of enumeration options. - (NSIndexSet *)indexesOfObjectsAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 62Parameters indexSet The indexes of the objects over which to enumerate. 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). predicate 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. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The indexes whose corresponding values in the array pass the test specified by predicate. If no objects in the array pass the test, returns an empty index set. Discussion By default, the enumeration starts with the first object and continues serially through the array to the last element specified by indexSet. You can specify NSEnumerationConcurrent and/or NSEnumerationReverse as enumeration options to modify this behavior. Important If the Block parameter or the indexSet is nil this method will raise an exception. Availability Available in iOS 4.0 and later. Declared in NSArray.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 63indexesOfObjectsPassingTest: Returns the indexes of objects in the array that pass a test in a given Block. - (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate Parameters predicate 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. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The indexes whose corresponding values in the array pass the test specified by predicate. If no objects in the array pass the test, returns an empty index set. Availability Available in iOS 4.0 and later. Declared in NSArray.h indexesOfObjectsWithOptions:passingTest: Returns the indexes of objects in the array that pass a test in a given Block for a given set of enumeration options. - (NSIndexSet *)indexesOfObjectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 64Parameters 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). predicate 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. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The indexes whose corresponding values in the array pass the test specified by predicate. If no objects in the array pass the test, returns an empty index set. Discussion By default, the enumeration starts with the first object and continues serially through the array to the last object. You can specify NSEnumerationConcurrent (page 2268) and/or NSEnumerationReverse (page 2268) as enumeration options to modify this behavior. Important If the Block parameter is nil this method will raise an exception. Availability Available in iOS 4.0 and later. Declared in NSArray.h indexOfObject: Returns the lowest index whose corresponding array value is equal to a given object. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 65- (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: (page 2122) 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. Availability Available in iOS 2.0 and later. See Also – containsObject: (page 52) – indexOfObjectIdenticalTo: (page 70) Declared in NSArray.h 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 Parameters anObject An object. range The range of indexes in the array 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. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 66Discussion Starting at index 0, each element of the array is sent an isEqual: (page 2122) 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: returns YES. This method raises an NSRangeException (page 2292) exception if the range parameter represents a range that doesn’t exist in the array. Availability Available in iOS 2.0 and later. See Also – containsObject: (page 52) – indexOfObjectIdenticalTo:inRange: (page 70) Declared in NSArray.h indexOfObject:inSortedRange:options:usingComparator: Returns the index, within a specified range, of an object compared with elements in the array using a given NSComparator block. - (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp Parameters obj An object for which to search in the array. If this value is nil, throws an NSInvalidArgumentException (page 2292). r The range within the array to search for obj. If r exceeds the bounds of the array (if the location plus length of the range is greater than the count of the array), throws an NSRangeException (page 2292). opts Options for the search. For possible values, see “NSBinarySearchingOptions” (page 96). If you specify both NSBinarySearchingFirstEqual (page 97) and NSBinarySearchingLastEqual (page 97), throws an NSInvalidArgumentException. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 67cmp A comparator block used to compare the object obj with elements in the array. If this value is NULL, throws an NSInvalidArgumentException (page 2292). Return Value If the NSBinarySearchingInsertionIndex (page 97) option is not specified: ● If the obj is found and neither NSBinarySearchingFirstEqual (page 97) nor NSBinarySearchingLastEqual (page 97) is specified, returns an arbitrary matching object's index. ● If the NSBinarySearchingFirstEqual (page 97) option is also specified, returns the lowest index of equal objects. ● If the NSBinarySearchingLastEqual (page 97) option is also specified, returns the highest index of equal objects. ● If the object is not found, returns NSNotFound. If the NSBinarySearchingInsertionIndex (page 97) option is specified, returns the index at which you should insert obj in order to maintain a sorted array: ● If the obj is found and neither NSBinarySearchingFirstEqual (page 97) nor NSBinarySearchingLastEqual (page 97) is specified, returns any equal or one larger index than any matching object’s index. ● If the NSBinarySearchingFirstEqual (page 97) option is also specified, returns the lowest index of equal objects. ● If the NSBinarySearchingLastEqual (page 97) option is also specified, returns the highest index of equal objects. ● If the object is not found, returns the index of the least greater object, or the index at the end of the array if the object is larger than all other elements. Special Considerations The elements in the array must have already been sorted using the comparator cmp. If the array is not sorted, the result is undefined. Availability Available in iOS 4.0 and later. Declared in NSArray.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 68indexOfObjectAtIndexes:options:passingTest: Returns the index, from a given set of indexes, of the first object in the array that passes a test in a given Block for a given set of enumeration options. - (NSUInteger)indexOfObjectAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate Parameters indexSet The indexes of the objects over which to enumerate. 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). predicate 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. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The lowest index whose corresponding value in the array passes the test specified by predicate. If no objects in the array pass the test, returns NSNotFound. Discussion By default, the enumeration starts with the first object and continues serially through the array to the last element specified by indexSet. You can specify NSEnumerationConcurrent (page 2268) and/or NSEnumerationReverse (page 2268) as enumeration options to modify this behavior. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 69Important If the Block parameter or indexSet is nil this method will raise an exception. Availability Available in iOS 4.0 and later. Declared in NSArray.h indexOfObjectIdenticalTo: Returns the lowest index whose corresponding array value is identical to a given object. - (NSUInteger)indexOfObjectIdenticalTo:(id)anObject Parameters anObject An object. Return Value The lowest index whose corresponding array value is identical to anObject. If none of the objects in the array is identical to anObject, returns NSNotFound. Discussion Objects are considered identical if their object addresses are the same. Availability Available in iOS 2.0 and later. See Also – containsObject: (page 52) – indexOfObject: (page 65) Declared in NSArray.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 NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 70Parameters anObject An object. range The range of indexes in the array 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 iOS 2.0 and later. See Also – containsObject: (page 52) – indexOfObject:inRange: (page 66) Declared in NSArray.h indexOfObjectPassingTest: Returns the index of the first object in the array that passes a test in a given Block. - (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 71Parameters predicate 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. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The lowest index whose corresponding value in the array passes the test specified by predicate. If no objects in the array pass the test, returns NSNotFound. Discussion If the Block parameter is nil this method will raise an exception. Availability Available in iOS 4.0 and later. Declared in NSArray.h indexOfObjectWithOptions:passingTest: Returns the index of an object in the array that passes a test in a given Block for a given set of enumeration options. - (NSUInteger)indexOfObjectWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 72Parameters 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). predicate 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. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The index whose corresponding value in the array passes the test specified by predicate and opts. If the opts bitmask specifies reverse order, then the last item that matches is returned. Otherwise, the index of the first matching object is returned. If no objects in the array pass the test, returns NSNotFound. 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/or NSEnumerationReverse as enumeration options to modify this behavior. Important If the Block parameter is nil this method will raise an exception. Availability Available in iOS 4.0 and later. Declared in NSArray.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 73initWithArray: Initializes a newly allocated array by placing in it the objects contained in a given array. - (id)initWithArray:(NSArray *)anArray Parameters anArray 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 iOS 2.0 and later. See Also + arrayWithObject: (page 46) – initWithObjects: (page 77) Declared in NSArray.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 Parameters array An array containing the objects with which to initialize the new array. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 74flag If YES, each object in array receives a copyWithZone: (page 1209) message to create a copy of the object—objects must conform to the NSCopying protocol. 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 when it is added to the returned array. Return Value An array initialized to contain the objects—or if flag is YES, copies of the objects—in 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. The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected. Availability Available in iOS 2.0 and later. See Also – initWithArray: (page 74) + arrayWithObject: (page 46) – initWithObjects: (page 77) Declared in NSArray.h initWithContentsOfFile: Initializes a newly allocated array with the contents of the file specified by a given path. - (id)initWithContentsOfFile:(NSString *)aPath Parameters aPath The path to a file containing a string representation of an array produced by the writeToFile:atomically: (page 95) method. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 75Return Value An array initialized to contain the contents of the file specified by aPath or nil if the file can’t be opened or the contents of the file can’t 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). The objects contained by this array are immutable, even if the array is mutable. Availability Available in iOS 2.0 and later. See Also + arrayWithContentsOfFile: (page 45) – writeToFile:atomically: (page 95) Declared in NSArray.h initWithContentsOfURL: Initializes a newly allocated array with the contents of the location specified by a given URL. - (id)initWithContentsOfURL:(NSURL *)aURL Parameters aURL The location of a file containing a string representation of an array produced by the writeToURL:atomically: (page 95) method. Return Value An array initialized to contain the contents specified by aURL. Returns nil if the location can’t be opened or if the contents of the location can’t 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). The objects contained by this array are immutable, even if the array is mutable. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 76Availability Available in iOS 2.0 and later. See Also + arrayWithContentsOfURL: (page 45) – writeToURL:atomically: (page 95) Declared in NSArray.h initWithObjects: Initializes a newly allocated array by placing in it the objects in the argument list. - (id)initWithObjects:(id)firstObj, ... Parameters firstObj, ... 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 can’t be modified. Availability Available in iOS 2.0 and later. See Also – initWithObjects:count: (page 77) + arrayWithObjects: (page 47) – initWithArray: (page 74) Declared in NSArray.h initWithObjects:count: Initializes a newly allocated array to include a given number of objects from a given C array. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 77- (id)initWithObjects:(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 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 can’t be modified. Availability Available in iOS 2.0 and later. See Also – initWithObjects: (page 77) + arrayWithObjects: (page 47) – initWithArray: (page 74) Declared in NSArray.h isEqualToArray: Compares the receiving array to another array. - (BOOL)isEqualToArray:(NSArray *)otherArray Parameters otherArray An array. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 78Return Value YES if the contents of otherArray are equal to the contents of the receiving array, 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 2122) test. Availability Available in iOS 2.0 and later. Declared in NSArray.h lastObject Returns 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 iOS 2.0 and later. See Also removeLastObject (page 941) (NSMutableArray) Related Sample Code WeatherMap Declared in NSArray.h 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 NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 79Parameters 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. Discussion This method raises an NSInvalidArgumentException if aSelector is NULL. Availability Available in iOS 2.0 and later. See Also – makeObjectsPerformSelector:withObject: (page 80) Related Sample Code LazyTableImages Declared in NSArray.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 Parameters aSelector A selector that identifies the message to send to the objects in the array. 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 iOS 2.0 and later. See Also – makeObjectsPerformSelector: (page 79) NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 80Declared in NSArray.h 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 (page 2292) is raised. Availability Available in iOS 2.0 and later. See Also – count (page 53) – objectsAtIndexes: (page 82) Related Sample Code DrillDownSave PVRTextureLoader SpeakHere TableViewSuite TheElements Declared in NSArray.h objectEnumerator Returns an enumerator object that lets you access each object in the array. - (NSEnumerator *)objectEnumerator NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 81Return 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. Availability Available in iOS 2.0 and later. See Also – reverseObjectEnumerator (page 86) nextObject (page 505) (NSEnumerator) Related Sample Code Birthdays Declared in NSArray.h objectsAtIndexes: Returns an array containing the objects in the array at the indexes specified by a given index set. - (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 82Return Value An array containing the objects in the array 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 (page 2292) if any location in indexes exceeds the bounds of the array, of if indexes is nil. Availability Available in iOS 2.0 and later. See Also – count (page 53) – objectAtIndex: (page 81) Declared in NSArray.h 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. Availability Available in iOS 2.0 and later. Declared in NSPathUtilities.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 83removeObserver:forKeyPath: Raises an exception. - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath Parameters observer The object to remove as an observer. keyPath A key-path, relative to the array, for which observer is registered to receive KVO change notifications. This value must not be nil. Special Considerations NSArray 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 iOS 2.0 and later. See Also – addObserver:forKeyPath:options:context: (page 49) – removeObserver:fromObjectsAtIndexes:forKeyPath: (page 85) Declared in NSKeyValueObserving.h removeObserver:forKeyPath:context Raises an exception. - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath Parameters observer The object to remove as an observer. keyPath A key-path, relative to the set, for which observer is registered to receive KVO change notifications. This value must not be nil. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 84context The context passed to the notifications. Special Considerations NSArray objects are not observable, so this method raises an exception when invoked on an NSArray object. Instead of observing a array, observe the ordered to-many relationship for which the array is the collection of related objects. See Also – addObserver:forKeyPath:options:context: (page 49) – removeObserver:forKeyPath: (page 84) removeObserver:fromObjectsAtIndexes:forKeyPath: Removes anObserver from all key value observer notifications associated with the specified keyPath relative to the array’s objects at indexes. - (void)removeObserver:(NSObject *)anObserver fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath Parameters anObserver The observer. indexes The index set. keyPath The key path, relative to the array, to be observed. Discussion This is not merely a convenience method; invoking this method is potentially much faster than repeatedly invoking removeObserver:forKeyPath: (page 2084). Availability Available in iOS 2.0 and later. See Also – addObserver:toObjectsAtIndexes:forKeyPath:options:context: (page 50) Declared in NSKeyValueObserving.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 85removeObserver:fromObjectsAtIndexes:forKeyPath:context: Raises an exception. - (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath context:(void *)context Parameters observer The object to remove as an observer. keyPath A key-path, relative to the array, for which observer is registered to receive KVO change notifications. This value must not be nil. context The context passed to the notifications. Special Considerations NSArray 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 iOS 5.0 and later. See Also – addObserver:forKeyPath:options:context: (page 49) – removeObserver:fromObjectsAtIndexes:forKeyPath: (page 85) Declared in NSKeyValueObserving.h reverseObjectEnumerator Returns an enumerator object that lets you access each object in the array, in reverse order. - (NSEnumerator *)reverseObjectEnumerator Return Value An enumerator object that lets you access each object in the array, in order, from the element at the highest index down to the element at index 0. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 86Special 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. Availability Available in iOS 2.0 and later. See Also – objectEnumerator (page 81) nextObject (page 505) (NSEnumerator) Declared in NSArray.h 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. Availability Available in iOS 2.0 and later. See Also – valueForKey: (page 94) Declared in NSKeyValueCoding.h sortedArrayHint Analyzes the array and returns a “hint” that speeds the sorting of the array when the hint is supplied to sortedArrayUsingFunction:context:hint: (page 90). NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 87- (NSData *)sortedArrayHint Availability Available in iOS 2.0 and later. See Also – sortedArrayUsingFunction:context:hint: (page 90) Declared in NSArray.h 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. Availability Available in iOS 4.0 and later. Declared in NSArray.h sortedArrayUsingDescriptors: Returns a copy of the receiving array sorted as specified by a given array of sort descriptors. - (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors Parameters sortDescriptors An array of NSSortDescriptor objects. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 88Return Value A copy of the receiving array sorted as specified by sortDescriptors. Discussion The first descriptor specifies the primary key path to be used in sorting the receiving array’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information. Availability Available in iOS 2.0 and later. See Also – sortedArrayUsingSelector: (page 91) – sortedArrayUsingFunction:context: (page 89) – sortedArrayUsingFunction:context:hint: (page 90) Declared in NSSortDescriptor.h sortedArrayUsingFunction:context: Returns a new array that lists the receiving array’s 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 receiving array’s 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, it’s 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]; NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 89if (v1 < v2) return NSOrderedAscending; else if (v1 > v2) 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 iOS 2.0 and later. See Also – sortedArrayUsingDescriptors: (page 88) – sortedArrayUsingFunction:context:hint: (page 90) – sortedArrayUsingSelector: (page 91) Related Sample Code Birthdays International Mountains QuartzDemo Declared in NSArray.h sortedArrayUsingFunction:context:hint: Returns a new array that lists the receiving array’s 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 receiving array’s elements, not copies of them. NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 90This method is similar to sortedArrayUsingFunction:context: (page 89), 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 don’t 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 87). 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 87) 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 90) sorts the array in O(P*LOG(P)+N) where P is the number of adds or deletes. This is an improvement over the un-hinted 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}. Availability Available in iOS 2.0 and later. See Also – sortedArrayUsingDescriptors: (page 88) – sortedArrayUsingFunction:context: (page 89) – sortedArrayUsingSelector: (page 91) Declared in NSArray.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 NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 91Parameters 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: (page 1554) 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 iOS 2.0 and later. See Also – sortedArrayUsingDescriptors: (page 88) – sortedArrayUsingFunction:context: (page 89) – sortedArrayUsingFunction:context:hint: (page 90) Related Sample Code TableViewSuite Declared in NSArray.h sortedArrayWithOptions:usingComparator: 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 Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 92- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr Parameters opts A bitmask that specifies the options for the sort (whether it should be performed concurrently and whether it should be performed stably). 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. Availability Available in iOS 4.0 and later. Declared in NSArray.h 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; NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 93theRange.location = 0; theRange.length = [wholeArray count] / 2; halfArray = [wholeArray subarrayWithRange:theRange]; Availability Available in iOS 2.0 and later. Related Sample Code DrillDownSave Declared in NSArray.h valueForKey: Returns an array containing the results of invoking valueForKey: using key on each of the array's objects. - (id)valueForKey:(NSString *)key Parameters key The key to retrieve. Return Value The value of the retrieved key. Discussion The returned array contains NSNull elements for each object that returns nil. Availability Available in iOS 2.0 and later. See Also – setValue:forKey: (page 87) Declared in NSKeyValueCoding.h NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 94writeToFile: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 (page 1634) 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 (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 45) or the instance method initWithContentsOfFile: (page 75). 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 iOS 2.0 and later. See Also – initWithContentsOfFile: (page 75) Declared in NSArray.h writeToURL:atomically: Writes the contents of the array to the location specified by a given URL. - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag NSArray Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 95Parameters aURL The location at which to write the array. 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, won’t be corrupted even if the system should crash during writing. Return Value YES if the location is written successfully, otherwise NO. Discussion If the array’s 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 45) or the instance method initWithContentsOfURL: (page 76). Availability Available in iOS 2.0 and later. See Also – initWithContentsOfURL: (page 76) Declared in NSArray.h Constants NSBinarySearchingOptions Optionsforsearchesandinsertionsusing indexOfObject:inSortedRange:options:usingComparator: (page 67). NSArray Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 96enum { NSBinarySearchingFirstEqual = (1 << 8), NSBinarySearchingLastEqual = (1 << 9), NSBinarySearchingInsertionIndex = (1 << 10), }; typedef NSUInteger NSBinarySearchingOptions; Constants NSBinarySearchingFirstEqual Specifies that the search should return the first object in the range that is equal to the given object. Available in iOS 4.0 and later. Declared in NSArray.h. NSBinarySearchingLastEqual Specifies that the search should return the last object in the range that is equal to the given object. Available in iOS 4.0 and later. Declared in NSArray.h. NSBinarySearchingInsertionIndex Returns the index at which you should insert the object in order to maintain a sorted array. Available in iOS 4.0 and later. Declared in NSArray.h. NSArray Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 97Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSException.h Companion guide Assertions and Logging Programming Guide Overview NSAssertionHandler 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 macros—you rarely need to invoke NSAssertionHandler methods directly. The macros for use inside methods and functions send handleFailureInMethod:object:file:lineNumber:description: (page 100) and handleFailureInFunction:file:lineNumber:description: (page 100) messages respectively to the current assertion handler. The assertion handler for the current thread is obtained using the currentHandler (page 99) class method. See NSAssertionHandlerKey (page 101) if you need to customize the behavior of NSAssertionHandler. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 98 NSAssertionHandler Class ReferenceTasks Handling Assertion Failures + currentHandler (page 99) Returns the NSAssertionHandler object associated with the current thread. – handleFailureInFunction:file:lineNumber:description: (page 100) Logs (using NSLog) an error message that includes the name of the function, the name of the file, and the line number. – handleFailureInMethod:object:file:lineNumber:description: (page 100) Logs (using NSLog) an error message that includes the name of the method that failed, the class name of the object, the name of the source file, and the line number. Class Methods currentHandler Returns the NSAssertionHandler object associated with the current thread. + (NSAssertionHandler *)currentHandler Return Value The NSAssertionHandler object associated with the current thread. Discussion If no assertion handler is associated with the current thread, this method creates one and assigns it to the thread. Availability Available in iOS 2.0 and later. Declared in NSException.h NSAssertionHandler Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 99Instance Methods handleFailureInFunction:file:lineNumber:description: Logs (using NSLog) an error message that includes the name of the function, the name of the file, and the line number. - (void)handleFailureInFunction:(NSString *)functionName file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format, ... Parameters functionName The function that failed. object The object that failed. fileName The name of the source file. line The line in which the failure occurred. format,... A format string followed by a comma-separated list of arguments to substitute into the format string. See Formatting String Objects for more information. Discussion Raises NSInternalInconsistencyException. Availability Available in iOS 2.0 and later. Declared in NSException.h handleFailureInMethod:object:file:lineNumber:description: Logs (using NSLog) an error message that includes the name of the method that failed, the class name of the object, the name of the source file, and the line number. - (void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format, ... NSAssertionHandler Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 100Parameters selector The selector for the method that failed object The object that failed. fileName The name of the source file. line The line in which the failure occurred. format,... A format string followed by a comma-separated list of arguments to substitute into the format string. See Formatting String Objects for more information. Discussion Raises NSInternalInconsistencyException. Availability Available in iOS 2.0 and later. Declared in NSException.h Constants The string constants for exceptions are listed and described in the Exceptions section of the Foundation Constants Reference. NSAssertionHandlerKey This constant refers to a key in the thread dictionary of the per-thread assertion handler object NSString * const NSAssertionHandlerKey; Constants NSAssertionHandlerKey A key with a corresponding value in the thread dictionary. If you need to customize the behavior of NSAssertionHandler, create a subclass, overriding handleFailureInMethod:object:file:lineNumber:description: (page 100) and handleFailureInFunction:file:lineNumber:description: (page 100), and install your instance into the current thread’s attributes dictionary with this key. NSAssertionHandler Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 101Inherits from NSObject Conforms to NSCoding NSCopying NSMutableCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 3.2 and later. Declared in Foundation/NSAttributedString.h Companion guide Attributed String Programming Guide Overview NSAttributedString objects manage character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string. The cluster’s two public classes, NSAttributedString and NSMutableAttributedString, declare the programmatic interface for read-only attributed strings and modifiable attributed strings, respectively. The Foundation framework defines only the basic functionality for attributed strings; in Mac OS X, additional methods supporting RTF, graphics attributes, and drawing attributed strings are described in NSAttributedString Application Kit Additions Reference, found in the Application Kit. The Application Kit also uses a subclass of NSMutableAttributedString, called NSTextStorage, to provide the storage for the Application Kit’s extended text-handling system. In Mac OS X, the Application Kit also uses NSParagraphStyle and its subclass NSMutableParagraphStyle to encapsulate the paragraph or ruler attributes used by the NSAttributedString classes. An attributed string identifies attributes by name, storing a value under the name in an NSDictionary object. In Mac OS X, standard attribute keys are described in the “Constants” section of NSAttributedString Application Kit Additions Reference. You can also assign any attribute name/value pair you wish to a range of characters—it 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 102 NSAttributedString Class Referenceis up to your application to interpret custom attributes (see Attributed String Programming Guide). If you are using attributed strings with the Core Text framework, you can also use the attribute keys defined by that framework. Note that the default font for NSAttributedString objects is Helvetica 12-point, which differs from the Mac OS X system font Lucida Grande, so you may wish to create the string with non-default attributes suitable for your application using, for example, initWithString:attributes: (page 113). Be aware that isEqual: comparison among NSAttributedString objects compares for exact equality, including not only literal character-by-character string equality but also equality of all attributes, which is not likely to be achieved in the case of many attributes such as attachments, lists, and tables, for example. iOS Note In iOS, you use this class almost exclusively in conjunction with the Core Text framework. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSMutableCopying mutableCopyWithZone: (page 2103) Tasks Creating an NSAttributedString Object – initWithString: (page 112) Returns an NSAttributedString object initialized with the characters of a given string and no attribute information. – initWithAttributedString: (page 112) Returns an NSAttributedString object initialized with the characters and attributes of another given attributed string. – initWithString:attributes: (page 113) Returns an NSAttributedString object initialized with a given string and attributes. NSAttributedString Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 103Retrieving Character Information – string (page 114) Returns the character contents of the receiver as an NSString object. – length (page 114) Returns the length of the receiver’s string object. Retrieving Attribute Information – attributesAtIndex:effectiveRange: (page 108) Returns the attributes for the character at a given index. – attributesAtIndex:longestEffectiveRange:inRange: (page 108) Returns the attributes for the character at a given index, and by reference the range over which the attributes apply. – attribute:atIndex:effectiveRange: (page 105) Returns the value for an attribute with a given name of the character at a given index, and by reference the range over which the attribute applies. – attribute:atIndex:longestEffectiveRange:inRange: (page 106) Returns the value for the attribute with a given name of the character at a given index, and by reference the range over which the attribute applies. Comparing Attributed Strings – isEqualToAttributedString: (page 113) Returns a Boolean value that indicates whether the receiver is equal to another given attributed string. Extracting a Substring – attributedSubstringFromRange: (page 107) Returns an NSAttributedString object consisting of the characters and attributes within a given range in the receiver. NSAttributedString Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 104Enumerating over Attributes in a String – enumerateAttribute:inRange:options:usingBlock: (page 109) Executes the Block for the specified attribute run in the specified range. – enumerateAttributesInRange:options:usingBlock: (page 111) Executes the Block for each attribute in the range. Instance Methods attribute:atIndex:effectiveRange: Returns the value for an attribute with a given name of the character at a given index, and by reference the range over which the attribute applies. - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange Parameters attributeName The name of an attribute. index The index for which to return attributes. This value must not exceed the bounds of the receiver. aRange If non-NULL: ● If the named attribute exists at index, upon return aRange contains a range over which the named attribute’s value applies. ● If the named attribute does not exist at index, upon return aRange contains the range over which the attribute does not exist. The range isn’t necessarily the maximum range covered by attributeName, and its extent is implementation-dependent. If you need the maximum range, use attribute:atIndex:longestEffectiveRange:inRange: (page 106). If you don't need this value, pass NULL. Return Value The value for the attribute named attributeName of the character at index index, or nil if there is no such attribute. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 105Discussion Raises an NSRangeException if index lies beyond the end of the receiver’s characters. For information about where to find the attribute keys for the returned dictionary, see the overview section of this document. Availability Available in iOS 3.2 and later. See Also – attributesAtIndex:effectiveRange: (page 108) Declared in NSAttributedString.h attribute:atIndex:longestEffectiveRange:inRange: Returns the value for the attribute with a given name of the character at a given index, and by reference the range over which the attribute applies. - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit Parameters attributeName The name of an attribute. index The index at which to test for attributeName. aRange If non-NULL: ● If the named attribute exists at index, upon return aRange contains the full range over which the value of the named attribute is the same as that at index, clipped to rangeLimit. ● If the named attribute does not exist at index, upon return aRange contains the full range over which the attribute does not exist, clipped to rangeLimit. If you don't need this value, pass NULL. rangeLimit The range over which to search for continuous presence of attributeName. This value must not exceed the bounds of the receiver. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 106Return Value The value for the attribute named attributeName of the character at index, or nil if there is no such attribute. Discussion Raises an NSRangeException if index or any part of rangeLimit lies beyond the end of the receiver’s characters. If you don’t need the longest effective range, it’s far more efficient to use the attribute:atIndex:effectiveRange: (page 105) method to retrieve the attribute value. For information about where to find the attribute keys for the returned dictionary, see the overview section of this document. Availability Available in iOS 3.2 and later. See Also – attributesAtIndex:longestEffectiveRange:inRange: (page 108) Declared in NSAttributedString.h attributedSubstringFromRange: Returns an NSAttributedString object consisting of the characters and attributes within a given range in the receiver. - (NSAttributedString *)attributedSubstringFromRange:(NSRange)aRange Parameters aRange The range from which to create a new attributed string. aRange must lie within the bounds of the receiver. Return Value An NSAttributedString object consisting of the characters and attributes within aRange in the receiver. Discussion Raises an NSRangeException if any part of aRange lies beyond the end of the receiver’s characters. This method treats the length of the string as a valid range value that returns an empty string. Availability Available in iOS 3.2 and later. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 107Declared in NSAttributedString.h attributesAtIndex:effectiveRange: Returns the attributes for the character at a given index. - (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)aRange Parameters index The index for which to return attributes. This value must lie within the bounds of the receiver. aRange Upon return, the range over which the attributes and values are the same as those at index. This range isn’t necessarily the maximum range covered, and its extent is implementation-dependent. If you need the maximum range, use attributesAtIndex:longestEffectiveRange:inRange: (page 108). If you don't need this value, pass NULL. Return Value The attributes for the character at index. Discussion Raises an NSRangeException if index lies beyond the end of the receiver’s characters. For information about where to find the attribute keys for the returned dictionary, see the overview section of this document. Availability Available in iOS 3.2 and later. See Also – attribute:atIndex:effectiveRange: (page 105) Declared in NSAttributedString.h attributesAtIndex:longestEffectiveRange:inRange: Returns the attributes for the character at a given index, and by reference the range over which the attributes apply. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 108- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit Parameters index The index for which to return attributes. This value must not exceed the bounds of the receiver. aRange If non-NULL, upon return contains the maximum range over which the attributes and values are the same as those at index, clipped to rangeLimit. rangeLimit The range over which to search for continuous presence of the attributes at index. This value must not exceed the bounds of the receiver. Discussion Raises an NSRangeException if index or any part of rangeLimit lies beyond the end of the receiver’s characters. If you don’t need the range information, it’s far more efficient to use the attributesAtIndex:effectiveRange: (page 108) method to retrieve the attribute value. For information about where to find the attribute keys for the returned dictionary, see the overview section of this document. Availability Available in iOS 3.2 and later. See Also – attribute:atIndex:longestEffectiveRange:inRange: (page 106) Declared in NSAttributedString.h enumerateAttribute:inRange:options:usingBlock: Executes the Block for the specified attribute run in the specified range. - (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(id value, NSRange range, BOOL *stop))block NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 109Parameters attrName The name of an attribute. enumerationRange If non-NULL, contains the maximum range over which the attributes and values are enumerated, clipped to enumerationRange. opts The options used by the enumeration. The values can be combined using C-bitwise OR. The values are described in “NSAttributedStringEnumerationOptions” (page 115). block The Block to apply to ranges of the attribute in the attributed string. The Block takes three arguments: value The attrName value. range An NSRange indicating the run of the attribute. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. Discussion If this method is sent to an instance of NSMutableAttributedString, mutation (deletion, addition, or change) is allowed, as long as it is within the range provided to the block; after a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator basically assumes any change in length occurs in the specified range.) For example, if block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range. Availability Available in iOS 4.0 and later. Declared in NSAttributedString.h NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 110enumerateAttributesInRange:options:usingBlock: Executes the Block for each attribute in the range. - (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(NSAttributedStringEnumerationOptions)opts usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block Parameters enumerationRange If non-NULL, contains the maximum range over which the attributes and values are enumerated, clipped to enumerationRange. opts The options used by the enumeration. The values can be combined using C-bitwise OR. The values are described in “NSAttributedStringEnumerationOptions” (page 115). block The Block to apply to ranges of the attribute in the attributed string. The Block takes three arguments: attrs An NSDictionary that contains the attributes for the range. range An NSRange indicating the run of the attribute. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. Discussion If this method is sent to an instance of NSMutableAttributedString, mutation (deletion, addition, or change) is allowed, as long as it is within the range provided to the block; after a mutation, the enumeration continues with the range immediately following the processed range, after the length of the processed range is adjusted for the mutation. (The enumerator basically assumes any change in length occurs in the specified range.) For example, if block is called with a range starting at location N, and the block deletes all the characters in the supplied range, the next call will also pass N as the index of the range. Availability Available in iOS 4.0 and later. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 111Declared in NSAttributedString.h initWithAttributedString: ReturnsanNSAttributedStringobjectinitializedwiththecharactersandattributesofanothergivenattributed string. - (id)initWithAttributedString:(NSAttributedString *)attributedString Parameters attributedString An attributed string. Return Value An NSAttributedString object initialized with the characters and attributes of attributedString. The returned object might be different than the original receiver. Availability Available in iOS 3.2 and later. Declared in NSAttributedString.h initWithString: Returns an NSAttributedString object initialized with the characters of a given string and no attribute information. - (id)initWithString:(NSString *)aString Parameters aString The characters for the new object. Return Value An NSAttributedString object initialized with the characters of aString and no attribute information The returned object might be different than the original receiver. Availability Available in iOS 3.2 and later. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 112Declared in NSAttributedString.h initWithString:attributes: Returns an NSAttributedString object initialized with a given string and attributes. - (id)initWithString:(NSString *)aString attributes:(NSDictionary *)attributes Parameters aString The string for the new attributed string. attributes The attributes for the new attributed string. For information about where to find the attribute keys you can include in this dictionary, see the overview section of this document. Discussion Returns an NSAttributedString object initialized with the characters of aString and the attributes of attributes. The returned object might be different from the original receiver. Availability Available in iOS 3.2 and later. Declared in NSAttributedString.h isEqualToAttributedString: Returns a Boolean value that indicates whether the receiver is equal to another given attributed string. - (BOOL)isEqualToAttributedString:(NSAttributedString *)otherString Parameters otherString The attributed string with which to compare the receiver. Return Value YES if the receiver is equal to otherString, otherwise NO. Discussion Attributed strings must match in both characters and attributes to be equal. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 113Availability Available in iOS 3.2 and later. Declared in NSAttributedString.h length Returns the length of the receiver’s string object. - (NSUInteger)length Availability Available in iOS 3.2 and later. See Also length (page 1605) (NSString) Declared in NSAttributedString.h string Returns the character contents of the receiver as an NSString object. - (NSString *)string Return Value The character contents of the receiver as an NSString object. Discussion This method doesn’t strip out attachment characters; in Mac OS X, use the string method of NSText to extract just the linguistically significant characters. For performance reasons, this method returns the current backing store of the attributed string object. If you want to maintain a snapshot of this as you manipulate the returned string, you should make a copy of the appropriate substring. This primitive method must guarantee efficient access to an attributed string’s characters; subclasses should implement it to execute in O(1) time. Availability Available in iOS 3.2 and later. NSAttributedString Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 114Declared in NSAttributedString.h Constants Standard attribute keys are described in the “Constants” section of NSAttributedString Application Kit Additions Reference. NSAttributedStringEnumerationOptions These constants describe the options available to the enumerateAttribute:inRange:options:usingBlock: (page 109) and enumerateAttributesInRange:options:usingBlock: (page 111) methods. enum { NSAttributedStringEnumerationReverse = (1UL << 1), NSAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL << 20) }; typedef NSUInteger NSAttributedStringEnumerationOptions; Constants NSAttributedStringEnumerationReverse Causes the enumeration to occur in reverse. Available in iOS 4.0 and later. Declared in NSAttributedString.h. NSAttributedStringEnumerationLongestEffectiveRangeNotRequired If NSAttributedStringEnumerationLongestEffectiveRangeNotRequired option is supplied, then the longest effective range computation is not performed; the blocks may be invoked with consecutive attribute runs that have the same value. Available in iOS 4.0 and later. Declared in NSAttributedString.h. NSAttributedString Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 115Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in NSAutoreleasePool.h Companion guide Advanced Memory Management Programming Guide Related sample code AQOfflineRenderTest iPhoneExtAudioFileConvertTest ListAdder TableViewSuite XMLPerformance Overview The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 116 NSAutoreleasePool Class ReferenceImportant If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks instead. For example, in place of: NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init; // Code benefitting from a local autorelease pool. [pool release]; you would write: @autoreleasepool { // Code benefitting from a local autorelease pool. } @autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC. In a reference-counted environment (as opposed to one which uses garbage collection), an NSAutoreleasePool object contains objects that have received an autorelease (page 2119) message and when drained it sends a release (page 2128) message to each of those objects. Thus, sending autorelease (page 2119) instead of release (page 2128) to an object extends the lifetime of that object at least until the pool itself is drained (it may be longer if the object is subsequently retained). An object can be put into the same pool several times, in which case it receives a release (page 2128) message for each time it was put into the pool. In a reference counted environment, Cocoa expects there to be an autorelease pool always available. If a pool is not available, autoreleased objects do not get released and you leak memory. In this situation, your program will typically log suitable warning messages. The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint. You create an NSAutoreleasePool object with the usual alloc and init messages and dispose of it with drain (page 121) (or release (page 122)—to understand the difference, see “Garbage Collection” (page 118)). Since you cannot retain an autorelease pool (or autorelease it—see retain (page 122) and autorelease (page 120)), draining a pool ultimately has the effect of deallocating it. You should always drain an autorelease pool in the same context (invocation of a method or function, or body of a loop) that it was created. See Autorelease Pools for more details. NSAutoreleasePool Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 117Each thread (including the main thread) maintains its own stack of NSAutoreleasePool objects (see “Threads” (page 118)). As new pools are created, they get added to the top of the stack. When pools are deallocated, they are removed from the stack. Autoreleased objects are placed into the top autorelease pool for the current thread. When a thread terminates, it automatically drains all of the autorelease pools associated with itself. Threads If you are making Cocoa calls outside of the Application Kit’s main thread—for example if you create a Foundation-only application or if you detach a thread—you need to create your own autorelease pool. If your application or thread is long-lived and potentially generates a lot of autoreleased objects, you should periodically drain and create autorelease pools (like the Application Kit does on the main thread); otherwise, autoreleased objects accumulate and your memory footprint grows. If, however, your detached thread does not make Cocoa calls, you do not need to create an autorelease pool. Note If you are creating secondary threads using the POSIX thread APIs instead of NSThread objects, you cannot use Cocoa, including NSAutoreleasePool, unless Cocoa is in multithreading mode. Cocoa enters multithreading mode only after detaching its first NSThread object. To use Cocoa on secondary POSIX threads, your application must first detach at least one NSThread object, which can immediately exit. You can test whether Cocoa is in multithreading mode with the NSThread class method isMultiThreaded (page 1691). Garbage Collection In a garbage-collected environment, there is no need for autorelease pools. You may, however, write a framework that is designed to work in both a garbage-collected and reference-counted environment. In this case, you can use autorelease pools to hint to the collector that collection may be appropriate. In a garbage-collected environment, sending a drain (page 121) message to a pool triggers garbage collection if necessary; release (page 122), however, is a no-op. In a reference-counted environment, drain (page 121) has the same effect as release (page 122). Typically, therefore, you should use drain (page 121) instead of release (page 122). NSAutoreleasePool Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 118Tasks Managing a Pool – release (page 122) Releases and pops the receiver. – drain (page 121) In a reference-counted environment, releases and pops the receiver; in a garbage-collected environment, triggers garbage collection if the memory allocated since the last collection is greater than the current threshold. – autorelease (page 120) Raises an exception. – retain (page 122) Raises an exception. Adding an Object to a Pool + addObject: (page 119) Adds a given object to the active autorelease pool in the current thread. – addObject: (page 120) Adds a given object to the receiver Class Methods addObject: Adds a given object to the active autorelease pool in the current thread. + (void)addObject:(id)object Parameters object The object to add to the active autorelease pool in the current thread. Discussion The same object may be added several times to the active pool and, when the pool is deallocated, it will receive a release (page 2128) message for each time it was added. NSAutoreleasePool Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 119Normally you don’t invoke this method directly—you send autorelease (page 2119) to object instead. Availability Available in iOS 2.0 and later. See Also – addObject: (page 120) Declared in NSAutoreleasePool.h Instance Methods addObject: Adds a given object to the receiver - (void)addObject:(id)object Parameters object The object to add to the receiver. Discussion The same object may be added several times to the same pool; when the pool is deallocated, the object will receive a release (page 2128) message for each time it was added. Normally you don’t invoke this method directly—you send autorelease (page 2119) to object instead. Availability Available in iOS 2.0 and later. See Also + addObject: (page 119) Declared in NSAutoreleasePool.h autorelease Raises an exception. NSAutoreleasePool Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 120- (id)autorelease Return Value self. Discussion In a reference-counted environment, this method raises an exception. drain In a reference-counted environment, releases and pops the receiver; in a garbage-collected environment, triggers garbage collection if the memory allocated since the last collection is greater than the current threshold. - (void)drain Discussion In a reference-counted environment, this method behaves the same as release (page 2128). Since an autorelease pool cannot be retained (see retain (page 122)), this therefore causes the receiver to be deallocated. When an autorelease pool is deallocated, it sends a release (page 2128) message to all its autoreleased objects. If an object is added several times to the same pool, when the pool is deallocated it receives a release (page 2128) message for each time it was added. In a garbage-collected environment, this method ultimately calls objc_collect_if_needed. Special Considerations In a garbage-collected environment, release is a no-op, so unless you do not want to give the collector a hint it is important to use drain in any code that may be compiled for a garbage-collected environment. Availability Available in iOS 2.0 and later. Related Sample Code FastEnumerationSample ListAdder SimpleFTPSample SimpleNetworkStreams SimpleURLConnections Declared in NSAutoreleasePool.h NSAutoreleasePool Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 121release Releases and pops the receiver. - (void)release Discussion In a reference-counted environment, since an autorelease pool cannot be retained (see retain (page 122)), this method causes the receiver to be deallocated. When an autorelease pool is deallocated, it sends a release (page 2128) message to all its autoreleased objects. If an object is added several times to the same pool, when the pool is deallocated it receives a release (page 2128) message for each time it was added. In a garbage-collected environment, this method is a no-op. Special Considerations You should typically use drain (page 121) instead of release. See Also – drain (page 121) retain Raises an exception. - (id)retain Return Value self. Discussion In a reference-counted environment, this method raises an exception. NSAutoreleasePool Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 122Inherits from NSOperation : NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 4.0 and later. Declared in Foundation/NSOperation.h Companion guide Threading Programming Guide Overview The NSBlockOperation class is a concrete subclass of NSOperation that manages the concurrent execution of one or more blocks. You can use this object to execute several blocks at once without having to create separate operation objects for each. When executing more than one block, the operation itself is considered finished only when all blocks have finished executing. Blocks added to a block operation are dispatched with default priority to an appropriate work queue. The blocks themselves should not make any assumptions about the configuration of their execution environment. For more information about blocks, see Blocks Programming Topics. Tasks Managing the Blocks in the Operation + blockOperationWithBlock: (page 124) Creates and returns an NSBlockOperation object and adds the specified block to it. – addExecutionBlock: (page 124) Adds the specified block to the receiver’s list of blocks to perform. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 123 NSBlockOperation Class Reference– executionBlocks (page 125) Returns an array containing the blocks associated with the receiver. Class Methods blockOperationWithBlock: Creates and returns an NSBlockOperation object and adds the specified block to it. + (id)blockOperationWithBlock:(void (^)(void))block Parameters block The block to add to the new block operation object’s list. The block should take no parameters and have no return value. Return Value A new block operation object. Availability Available in iOS 4.0 and later. Declared in NSOperation.h Instance Methods addExecutionBlock: Adds the specified block to the receiver’s list of blocks to perform. - (void)addExecutionBlock:(void (^)(void))block Parameters block The block to add to the receiver’s list. The block should take no parameters and have no return value. Discussion The specified block should not make any assumptions about is execution environment. NSBlockOperation Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 124Calling this method while the receiver is executing or has already finished causes an NSInvalidArgumentException exception to be thrown. Availability Available in iOS 4.0 and later. Declared in NSOperation.h executionBlocks Returns an array containing the blocks associated with the receiver. - (NSArray *)executionBlocks Return Value An array of blocks. The blocks in this array are copies of the ones originally added using the addExecutionBlock: method. Availability Available in iOS 4.0 and later. Declared in NSOperation.h NSBlockOperation Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 125Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSBundle.h Companion guides Bundle Programming Guide Resource Programming Guide Related sample code BubbleLevel International Mountains iPhoneCoreDataRecipes oalTouch PhotoScroller Overview An NSBundle object represents a location in the file system that groups code and resources that can be used in a program. NSBundle objects locate program resources, dynamically load and unload executable code, and assist in localization. You build a bundle in Xcode using one of these project types: Application, Framework, plug-ins. Although bundle structures vary depending on the target platform and the type of bundle you are building, the NSBundle class hides this underlying structure in most (but not all) cases. Many of the methods you use to load resources from a bundle automatically locate the appropriate starting directory and look for resources in known places. For information about application bundle structures (for Mac OS X and iOS), see Bundle Programming Guide. For information about the structure of framework bundles, see Framework Programming Guide. For information about the structure of Mac OS X plug-ins, see Code Loading Programming Topics. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 126 NSBundle Class ReferenceFor additional information about how to load nib files and images in a Mac OS X application, see NSBundle Additions Reference. For information about how to load nib files in an iOS application, see NSBundle UIKit Additions Reference. Unlike some other Foundation classes with corresponding Core Foundation names (such as NSString and CFString), NSBundle objects cannot be cast (“toll-free bridged”) to CFBundle references. If you need functionality provided in CFBundle, you can still create a CFBundle and use the CFBundle Reference API. See “Interchangeable Data Types” for more information on toll-free bridging. Tasks Initializing an NSBundle + bundleWithURL: (page 135) Returns an NSBundle object that corresponds to the specified file URL. + bundleWithPath: (page 134) Returns an NSBundle object that corresponds to the specified directory. – initWithURL: (page 147) Returns an NSBundle object initialized to correspond to the specified file URL. – initWithPath: (page 146) Returns an NSBundle object initialized to correspond to the specified directory. Getting an NSBundle + bundleForClass: (page 133) Returns the NSBundle object with which the specified class is associated. + bundleWithIdentifier: (page 133) Returns the previously created NSBundle instance that has the specified bundle identifier. + mainBundle (page 135) Returns the NSBundle object that corresponds to the directory where the current application executable is located. + allBundles (page 132) Returns an array of all the application’s non-framework bundles. + allFrameworks (page 132) Returns an array of all of the application’s bundles that represent frameworks. NSBundle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 127Getting a Bundled Class – classNamed: (page 143) Returns the Class object for the specified name. – principalClass (page 160) Returns the receiver’s principal class. Finding Resources – URLForResource:withExtension:subdirectory: (page 168) Returns the file URL for the resource file identified by the specified name and extension and residing in a given bundle directory. + pathForResource:ofType:inDirectory: (page 136) Returns the full pathname for the resource file identified by the specified name and extension and residing in a given bundle directory. – URLForResource:withExtension: (page 167) Returns the file URL for the resource identified by the specified name and file extension. – pathForResource:ofType: (page 154) Returns the full pathname for the resource identified by the specified name and file extension. – URLsForResourcesWithExtension:subdirectory: (page 170) Returns the file URL for the resource identified by the specified name and file extension and located in the specified bundle subdirectory. – pathForResource:ofType:inDirectory: (page 155) Returns the full pathname for the resource identified by the specified name and file extension and located in the specified bundle subdirectory. – URLForResource:withExtension:subdirectory:localization: (page 169) Returns the file URL for the resource identified by the specified name and file extension, located in the specified bundle subdirectory, and limited to global resources and those associated with the specified localization. – pathForResource:ofType:inDirectory:forLocalization: (page 156) Returns the full pathname for the resource identified by the specified name and file extension, located in the specified bundle subdirectory, and limited to global resources and those associated with the specified localization. NSBundle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 128+ pathsForResourcesOfType:inDirectory: (page 137) Returns an array containing the pathnames for all bundle resources having the specified extension and residing in the bundle directory at the specified path. – pathsForResourcesOfType:inDirectory: (page 157) Returns an array containing the pathnames for all bundle resources having the specified filename extension and residing in the resource subdirectory. – URLsForResourcesWithExtension:subdirectory:localization: (page 170) Returns an array containing the file URLs for all bundle resources having the specified filename extension, residing in the specified resource subdirectory, and limited to global resources and those associated with the specified localization. – pathsForResourcesOfType:inDirectory:forLocalization: (page 158) Returns an array containing the file for all bundle resources having the specified filename extension, residing in the specified resource subdirectory, and limited to global resources and those associated with the specified localization. + URLForResource:withExtension:subdirectory:inBundleWithURL: (page 140) Creates and returns a file URL for the resource with the specified name and extension in the specified bundle. + URLsForResourcesWithExtension:subdirectory:inBundleWithURL: (page 140) Returns an array containing the file URLs for all bundle resources having the specified filename extension, residing in the specified resource subdirectory, within the specified bundle. – resourcePath (page 163) Returns the full pathname of the receiving bundle’s subdirectory containing resources. Getting the Bundle Directory – bundleURL (page 143) Returns the full URL of the receiver’s bundle directory. – bundlePath (page 142) Returns the full pathname of the receiver’s bundle directory. Getting Bundle Information – bundleIdentifier (page 142) Returns the receiver’s bundle identifier. NSBundle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 129– infoDictionary (page 146) Returns a dictionary that contains information about the receiver. – objectForInfoDictionaryKey: (page 153) Returns the value associated with the specified key in the receiver's information property list. – builtInPlugInsURL (page 142) Returns the file URL of the receiver's subdirectory containing plug-ins. – builtInPlugInsPath (page 141) Returns the full pathname of the receiver's subdirectory containing plug-ins. – executableURL (page 145) Returns the file URL of the receiver's executable file. – executablePath (page 145) Returns the full pathname of the receiver's executable file. – URLForAuxiliaryExecutable: (page 166) Returns the file URL of the executable with the specified name in the receiver’s bundle. – pathForAuxiliaryExecutable: (page 153) Returns the full pathname of the executable with the specified name in the receiver’s bundle. – privateFrameworksURL (page 162) Returns the file URL of the receiver's subdirectory containing private frameworks. – privateFrameworksPath (page 162) Returns the full pathname of the receiver's subdirectory containing private frameworks. – sharedFrameworksURL (page 164) Returns the file URL of the receiver's subdirectory containing shared frameworks. – sharedFrameworksPath (page 164) Returns the full pathname of the receiver's subdirectory containing shared frameworks. – sharedSupportURL (page 165) Returns the file URL of the receiver's subdirectory containing shared support files. – sharedSupportPath (page 165) Returns the full pathname of the receiver's subdirectory containing shared support files. – resourceURL (page 163) Returns the file URL of the receiver's subdirectory containing resource files. NSBundle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 130Managing Localized Resources – localizedStringForKey:value:table: (page 151) Returns a localized version of the string designated by the specified key and residing in the specified table. Loading a Bundle’s Code – executableArchitectures (page 144) Returns an array of numbers indicating the architecture types supported by the bundle’s executable. – preflightAndReturnError: (page 160) Returns a Boolean value indicating whether the bundle’s executable code could be loaded successfully. – load (page 148) Dynamically loads the bundle’s executable code into a running program, if the code has not already been loaded. – loadAndReturnError: (page 149) Loads the bundle’s executable code and returns any errors. – isLoaded (page 148) Obtains information about the load status of a bundle. – unload (page 165) Unloads the code associated with the receiver. Managing Localizations + preferredLocalizationsFromArray: (page 138) Returns one or more localizations from the specified list that a bundle object would use to locate resources for the current user. + preferredLocalizationsFromArray:forPreferences: (page 139) Returns the localizations that a bundle object would prefer, given the specified bundle and user preference localizations. – localizations (page 150) Returns a list of all the localizations contained within the receiver’s bundle. – developmentLocalization (page 144) Returns the localization used to create the bundle. NSBundle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 131– preferredLocalizations (page 159) Returns an array of strings indicating the actual localizations contained in the receiver’s bundle. – localizedInfoDictionary (page 151) Returns a dictionary with the keys from the bundle’s localized property list. Class Methods allBundles Returns an array of all the application’s non-framework bundles. + (NSArray *)allBundles Return Value An array of all the application’s non-framework bundles. Discussion The returned array includes the main bundle and all bundles that have been dynamically created but doesn’t contain any bundles that represent frameworks. Availability Available in iOS 2.0 and later. Declared in NSBundle.h allFrameworks Returns an array of all of the application’s bundles that represent frameworks. + (NSArray *)allFrameworks Return Value An array of all of the application’s bundles that represent frameworks. Only frameworks with one or more Objective-C classes in them are included. Discussion The returned array includes frameworks that are linked into an application when the application is built and bundles for frameworks that have been dynamically created. NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 132Availability Available in iOS 2.0 and later. Declared in NSBundle.h bundleForClass: Returns the NSBundle object with which the specified class is associated. + (NSBundle *)bundleForClass:(Class)aClass Parameters aClass A class. Return Value The NSBundle object that dynamically loaded aClass (a loadable bundle), the NSBundle object for the framework in which aClass is defined, or the main bundle object if aClass was not dynamically loaded or is not defined in a framework. Availability Available in iOS 2.0 and later. See Also + mainBundle (page 135) + bundleWithPath: (page 134) Related Sample Code ClockControlPalette Declared in NSBundle.h bundleWithIdentifier: Returns the previously created NSBundle instance that has the specified bundle identifier. + (NSBundle *)bundleWithIdentifier:(NSString *)identifier Parameters identifier The identifier for an existing NSBundle instance. NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 133Return Value The previously created NSBundle instance that has the bundle identifier identifier. Returns nil if the requested bundle is not found. Discussion This method is typically used by frameworks and plug-ins to locate their own bundle at runtime. This method may be somewhat more efficient than trying to locate the bundle using the bundleForClass: (page 133) method. Availability Available in iOS 2.0 and later. Declared in NSBundle.h bundleWithPath: Returns an NSBundle object that corresponds to the specified directory. + (NSBundle *)bundleWithPath:(NSString *)fullPath Parameters fullPath The path to a directory. This must be a full pathname for a directory; if it contains any symbolic links, they must be resolvable. Return Value The NSBundle object that corresponds to fullPath, or nil if fullPath does not identify an accessible bundle directory. Discussion This method allocates and initializes the returned object if there is no existing NSBundle associated with fullPath, in which case it returns the existing object. Availability Available in iOS 2.0 and later. See Also + mainBundle (page 135) + bundleForClass: (page 133) – initWithPath: (page 146) + bundleWithURL: (page 135) NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 134Declared in NSBundle.h bundleWithURL: Returns an NSBundle object that corresponds to the specified file URL. + (NSBundle *)bundleWithURL:(NSURL *)url Parameters url The URL to a directory. This must be a URL for a directory; if it contains any symbolic links, they must be resolvable. Return Value The NSBundle object that corresponds to url, or nil if url does not identify an accessible bundle directory. Discussion This method allocates and initializes the returned object if there is no existing NSBundle associated with url, in which case it returns the existing object. Availability Available in iOS 4.0 and later. See Also + bundleWithPath: (page 134) + bundleWithIdentifier: (page 133) + bundleForClass: (page 133) Declared in NSBundle.h mainBundle Returns the NSBundle object that corresponds to the directory where the current application executable is located. + (NSBundle *)mainBundle Return Value The NSBundle object that corresponds to the directory where the application executable is located, or nil if a bundle object could not be created. NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 135Discussion This method allocates and initializes a bundle object if one doesn’t already exist. The new object corresponds to the directory where the application executable is located. Be sure to check the return value to make sure you have a valid bundle. This method may return a valid bundle object even for unbundled applications. In general, the main bundle corresponds to an application file package or application wrapper: a directory that bears the name of the application and is marked by a “.app” extension. Availability Available in iOS 2.0 and later. See Also + bundleForClass: (page 133) + bundleWithPath: (page 134) Related Sample Code iPhoneCoreDataRecipes iPhoneMultichannelMixerTest oalTouch PhotoScroller QuartzDemo Declared in NSBundle.h pathForResource:ofType:inDirectory: Returns the full pathname for the resource file identified by the specified name and extension and residing in a given bundle directory. + (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension inDirectory:(NSString *)bundlePath Parameters name The name of a resource file contained in the directory specified by bundlePath. extension If extension is an empty string or nil, the extension is assumed not to exist and the file is the first file encountered that exactly matches name. bundlePath The path of a top-level bundle directory. This must be a valid path. For example, to specify the bundle directory for a Mac OS X application, you might specify the path /Applications/MyApp.app. NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 136Return Value The full pathname for the resource file or nil if the file could not be located. This method also returns nil if the bundle specified by the bundlePath parameter does not exist or is not a readable directory. Discussion The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics. Note This method is best suited only for the occasional retrieval of resource files. In most cases where you need to retrieve bundle resources, it is preferable to use the NSBundle instance methods instead. Availability Available in iOS 2.0 and later. See Also – localizedStringForKey:value:table: (page 151) – pathForResource:ofType: (page 154) – pathForResource:ofType:inDirectory: (page 155) + pathsForResourcesOfType:inDirectory: (page 137) – pathsForResourcesOfType:inDirectory: (page 157) – URLForResource:withExtension:subdirectory: (page 168) Declared in NSBundle.h pathsForResourcesOfType:inDirectory: Returns an array containing the pathnames for all bundle resources having the specified extension and residing in the bundle directory at the specified path. + (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)bundlePath NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 137Parameters extension The file extension. If extension is an empty string or nil, the extension is assumed not to exist, all the files in bundlePath are returned. bundlePath The top-level directory of a bundle. This must represent a valid path. Return Value An array containing the full pathnames for all bundle resources with the specified extension. This method returns an empty array if no matching resource files are found. It also returns an empty array if the bundle specified by the bundlePath parameter does not exist or is not a readable directory. Discussion This method provides a means for dynamically discovering multiple bundle resources of the same type. The method first looks for matching resource files in the nonlocalized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) It then looks in the top level of any available language-specific “.lproj” directories. It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics. Note This method is best suited only for the occasional retrieval of resource files. In most cases where you need to retrieve bundle resources, it is preferable to use the NSBundle instance methods instead. Availability Available in iOS 2.0 and later. See Also – localizedStringForKey:value:table: (page 151) – pathForResource:ofType: (page 154) – pathForResource:ofType:inDirectory: (page 155) Declared in NSBundle.h preferredLocalizationsFromArray: Returns one or more localizations from the specified list that a bundle object would use to locate resources for the current user. NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 138+ (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray Parameters localizationsArray An array of NSString objects, each of which specifies the name of a localization that the bundle supports. Return Value An array of NSString objects containing the preferred localizations. These strings are ordered in the array according to the current user's language preferences and are taken from the strings in the localizationsArray parameter. Availability Available in iOS 2.0 and later. Declared in NSBundle.h preferredLocalizationsFromArray:forPreferences: Returns the localizations that a bundle object would prefer, given the specified bundle and user preference localizations. + (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray forPreferences:(NSArray *)preferencesArray Parameters localizationsArray An array of NSString objects, each of which specifies the name of a localization that the bundle supports. preferencesArray An array of NSString objects containing the user's preferred localizations. If this parameter is nil, the method uses the current user's localization preferences. Return Value An array of NSString objects containing the preferred localizations. These strings are ordered in the array according to the specified preferences and are taken from the strings in the localizationsArray parameter. Discussion Use the argument localizationsArray to specify the supported localizations of the bundle and use preferencesArray to specify the user’s localization preferences. If none of the user-preferred localizations are available in the bundle, this method chooses one of the bundle localizations and returns it. NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 139Availability Available in iOS 2.0 and later. Declared in NSBundle.h URLForResource:withExtension:subdirectory:inBundleWithURL: Creates and returns a file URL for the resource with the specified name and extension in the specified bundle. + (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath inBundleWithURL:(NSURL *)bundleURL Parameters name The name of the resource file. extension If extension is an empty string or nil, the extension is assumed not to exist and the file URL is the first file encountered that exactly matches name. subpath The name of the bundle subdirectory to search. bundleURL The file URL of the bundle to search. Return Value The file URL for the resource file or nil if the file could not be located. Availability Available in iOS 4.0 and later. Declared in NSBundle.h URLsForResourcesWithExtension:subdirectory:inBundleWithURL: Returns an array containing the file URLs for all bundle resources having the specified filename extension, residing in the specified resource subdirectory, within the specified bundle. + (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath inBundleWithURL:(NSURL *)bundleURL NSBundle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 140Parameters ext The file extension of the files to retrieve. subpath The name of the bundle subdirectory to search. bundleURL The file URL of the bundle to search. Return Value The file URL for the resource file or nil if the file could not be located. Availability Available in iOS 4.0 and later. Declared in NSBundle.h Instance Methods builtInPlugInsPath Returns the full pathname of the receiver's subdirectory containing plug-ins. - (NSString *)builtInPlugInsPath Return Value The full pathname of the receiving bundle’s subdirectory containing plug-ins. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 2.0 and later. Declared in NSBundle.h NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 141builtInPlugInsURL Returns the file URL of the receiver's subdirectory containing plug-ins. - (NSURL *)builtInPlugInsURL Return Value The file URL of the receiving bundle’s subdirectory containing plug-ins. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a URL for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 4.0 and later. Declared in NSBundle.h bundleIdentifier Returns the receiver’s bundle identifier. - (NSString *)bundleIdentifier Return Value The receiver’s bundle identifier, which is defined by the CFBundleIdentifier key in the bundle’s information property list. Availability Available in iOS 2.0 and later. See Also – infoDictionary (page 146) Declared in NSBundle.h bundlePath Returns the full pathname of the receiver’s bundle directory. - (NSString *)bundlePath NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 142Return Value The full pathname of the receiver’s bundle directory. Availability Available in iOS 2.0 and later. Related Sample Code AppPrefs DrillDownSave International Mountains Declared in NSBundle.h bundleURL Returns the full URL of the receiver’s bundle directory. - (NSURL *)bundleURL Return Value The full URL of the receiver’s bundle directory. Availability Available in iOS 4.0 and later. Declared in NSBundle.h classNamed: Returns the Class object for the specified name. - (Class)classNamed:(NSString *)className Parameters className The name of a class. Return Value The Class object for className. Returns nil if className is not one of the classes associated with the receiver or if there is an error loading the executable code containing the class implementation. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 143Discussion If the bundle’s executable code is not yet loaded, this method dynamically loads it into memory. Classes (and categories) are loaded from just one file within the bundle directory; this code file has the same name as the directory, but without the extension (“.bundle”, “.app”, “.framework”). As a side effect of code loading, the receiver posts NSBundleDidLoadNotification (page 173) after all classes and categories have been loaded; see “Notifications” (page 173) for details. Availability Available in iOS 2.0 and later. See Also – principalClass (page 160) – load (page 148) Declared in NSBundle.h developmentLocalization Returns the localization used to create the bundle. - (NSString *)developmentLocalization Return Value The localization used to create the bundle. Discussion The returned localization corresponds to the value in the CFBundleDevelopmentRegion key of the bundle’s property list (Info.plist). Availability Available in iOS 2.0 and later. Declared in NSBundle.h executableArchitectures Returns an array of numbers indicating the architecture types supported by the bundle’s executable. - (NSArray *)executableArchitectures NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 144Return Value An array of NSNumber objects, each of which contains an integer value corresponding to a supported processor architecture. For a list of common architecture types, see the constants in “Mach-O Architecture” (page 171). If the bundle does not contain a Mach-O executable, this method returns nil. Discussion This method scans the bundle’s Mach-O executable and returns all of the architecture types it finds. Because they are taken directly from the executable, the returned values may not always correspond to one of the well-known CPU types defined in “Mach-O Architecture” (page 171). Availability Available in iOS 2.0 and later. Declared in NSBundle.h executablePath Returns the full pathname of the receiver's executable file. - (NSString *)executablePath Return Value The full pathname of the receiving bundle’s executable file. Availability Available in iOS 2.0 and later. Declared in NSBundle.h executableURL Returns the file URL of the receiver's executable file. - (NSURL *)executableURL Return Value The file URL of the receiving bundle’s executable file. Availability Available in iOS 4.0 and later. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 145Declared in NSBundle.h infoDictionary Returns a dictionary that contains information about the receiver. - (NSDictionary *)infoDictionary Return Value A dictionary, constructed from the bundle's Info.plist file, that contains information about the receiver. If the bundle does not contain an Info.plist file, a valid dictionary is returned but this dictionary contains only private keys that are used internally by the NSBundle class. The NSBundle class may add extra keys to this dictionary for its own use. Discussion Common keys for accessing the values of the dictionary are CFBundleIdentifier, NSMainNibFile, and NSPrincipalClass. Availability Available in iOS 2.0 and later. See Also – principalClass (page 160) dictionaryWithContentsOfFile: (page 462) (NSDictionary) Related Sample Code BubbleLevel Declared in NSBundle.h initWithPath: Returns an NSBundle object initialized to correspond to the specified directory. - (id)initWithPath:(NSString *)fullPath Parameters fullPath The path to a directory. This must be a full pathname for a directory; if it contains any symbolic links, they must be resolvable. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 146Return Value An NSBundle object initialized to correspond to fullPath. This method initializes and returns a new instance only if there is no existing bundle associated with fullPath, otherwise it deallocates self and returns the existing object. If fullPath doesn’t exist or the user doesn’t have access to it, returns nil. Discussion It’s not necessary to allocate and initialize an instance for the main bundle; use the mainBundle (page 135) class method to get this instance. You can also use the bundleWithPath: (page 134) class method to obtain a bundle identified by its directory path. Availability Available in iOS 2.0 and later. See Also + bundleForClass: (page 133) – initWithURL: (page 147) Declared in NSBundle.h initWithURL: Returns an NSBundle object initialized to correspond to the specified file URL. - (id)initWithURL:(NSURL *)url Parameters url The file URL to a directory. This must be a full URL for a directory; if it contains any symbolic links, they must be resolvable. Return Value An NSBundle object initialized to correspond to url. This method initializes and returns a new instance only if there is no existing bundle associated with url, otherwise it deallocates self and returns the existing object. If url doesn’t exist or the user doesn’t have access to it, returns nil. Discussion It’s not necessary to allocate and initialize an instance for the main bundle; use the mainBundle (page 135) class method to get this instance. You can also use the bundleWithURL: (page 135) class method to obtain a bundle identified by its file URL. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 147Availability Available in iOS 4.0 and later. See Also + bundleWithPath: (page 134) + bundleWithIdentifier: (page 133) + bundleForClass: (page 133) + bundleWithURL: (page 135) Declared in NSBundle.h isLoaded Obtains information about the load status of a bundle. - (BOOL)isLoaded Return Value YES if the bundle’s code is currently loaded, otherwise NO. Availability Available in iOS 2.0 and later. See Also – load (page 148) Declared in NSBundle.h load Dynamically loads the bundle’s executable code into a running program, if the code has not already been loaded. - (BOOL)load Return Value YES if the method successfully loads the bundle’s code or if the code has already been loaded, otherwise NO. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 148Discussion You can use this method to load the code associated with a dynamically loaded bundle, such as a plug-in or framework. Prior to Mac OS X version 10.5, a bundle would attempt to load its code—if it had any—only once. Once loaded, you could not unload that code. In Mac OS X version 10.5 and later, you can unload a bundle’s executable code using the unload (page 165) method. You don’t need to load a bundle’s executable code to search the bundle’s resources. Availability Available in iOS 2.0 and later. See Also – loadAndReturnError: (page 149) – isLoaded (page 148) – unload (page 165) – classNamed: (page 143) – principalClass (page 160) Declared in NSBundle.h loadAndReturnError: Loads the bundle’s executable code and returns any errors. - (BOOL)loadAndReturnError:(NSError **)error Parameters error On input, a pointer to an error object variable. On output, this variable may contain an error object indicating why the bundle’s executable could not be loaded. If no error occurred, this parameter is left unmodified. You may specify nil for this parameter if you are not interested in the error information. Return Value YES if the bundle’s executable code was loaded successfully or was already loaded; otherwise, NO if the code could not be loaded. Discussion If this method returns NO and you pass a value for the error parameter, a suitable error object is returned in that parameter. Potential errors returned are in the Cocoa error domain and include the types that follow. For a full list of error types, see FoundationErrors.h. ● NSFileNoSuchFileError - returned if the bundle’s executable file was not located. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 149 ● NSExecutableNotLoadableError - returned if the bundle’s executable file exists but could not be loaded. This error is returned if the executable is not recognized as a loadable executable. It can also be returned if the executable is a PEF/CFM executable but the current process does not support that type of executable. ● NSExecutableArchitectureMismatchError - returned if the bundle executable does not include code that matches the processor architecture of the current processor. ● NSExecutableRuntimeMismatchError - returned if the bundle’s required Objective-C runtime information is not compatible with the runtime of the current process. ● NSExecutableLoadError - returned if the bundle’s executable failed to load for some detectable reason prior to linking. This error might occur if the bundle depends on a framework or library that is missing or if the required framework or library is not compatible with the current architecture or runtime version. ● NSExecutableLinkError - returned if the executable failed to load due to link errors but is otherwise alright. The error object may contain additional debugging information in its description that you can use to identify the cause of the error. (This debugging information should not be displayed to the user.) You can obtain the debugging information by invoking the error object’s description method in your code or by using the print-object command on the error object in gdb. Availability Available in iOS 2.0 and later. See Also – load (page 148) – unload (page 165) Declared in NSBundle.h localizations Returns a list of all the localizations contained within the receiver’s bundle. - (NSArray *)localizations Return Value An array, containing NSString objects, that specifies all the localizations contained within the receiver’s bundle. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 150Availability Available in iOS 2.0 and later. Declared in NSBundle.h localizedInfoDictionary Returns a dictionary with the keys from the bundle’s localized property list. - (NSDictionary *)localizedInfoDictionary Return Value A dictionary with the keys from the bundle’s localized property list (InfoPlist.strings). Discussion This method uses the preferred localization for the current user when determining which resources to return. If the preferred localization is not available, this method chooses the most appropriate localization found in the bundle. Availability Available in iOS 2.0 and later. Related Sample Code BubbleLevel Declared in NSBundle.h localizedStringForKey:value:table: Returns a localized version of the string designated by the specified key and residing in the specified table. - (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName Parameters key The key for a string in the table identified by tableName. value The value to return if key is nil or if a localized string for key can’t be found in the table. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 151tableName The receiver’s string table to search. If tableName is nil or is an empty string, the method attempts to use the table in Localizable.strings. Return Value A localized version of the string designated by key in table tableName. If value is nil or an empty string, and a localized string is not found in the table, returns key. If key and value are both nil, returns the empty string. Discussion For more details about string localization and the specification of a .strings file, see ““String Resources”.” Using the user default NSShowNonLocalizedStrings, you can alter the behavior of localizedStringForKey:value:table: (page 151) to log a message when the method can’t find a localized string. If you set this default to YES (in the global domain or in the application’s domain), then when the method can’t find a localized string in the table, it logs a message to the console and capitalizes key before returning it. The following example cycles through a static array of keys when a button is clicked, gets the value for each key from a strings table named Buttons.strings, and sets the button title with the returned value: - (void)changeTitle:(id)sender { static int keyIndex = 0; NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; NSString *locString = [thisBundle localizedStringForKey:assortedKeys[keyIndex++] value:@"No translation" table:@"Buttons"]; [sender setTitle:locString]; if (keyIndex == MAXSTRINGS) keyIndex=0; } Availability Available in iOS 2.0 and later. See Also – pathForResource:ofType: (page 154) – pathForResource:ofType:inDirectory: (page 155) – pathsForResourcesOfType:inDirectory: (page 157) NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 152+ pathForResource:ofType:inDirectory: (page 136) + pathsForResourcesOfType:inDirectory: (page 137) Declared in NSBundle.h objectForInfoDictionaryKey: Returns the value associated with the specified key in the receiver's information property list. - (id)objectForInfoDictionaryKey:(NSString *)key Parameters key A key in the receiver's property list. Return Value The value associated with key in the receiver's property list (Info.plist). The localized value of a key is returned when one is available. Discussion Use of this method is preferred over other access methods because it returns the localized value of a key when one is available. Availability Available in iOS 2.0 and later. Declared in NSBundle.h pathForAuxiliaryExecutable: Returns the full pathname of the executable with the specified name in the receiver’s bundle. - (NSString *)pathForAuxiliaryExecutable:(NSString *)executableName Parameters executableName The name of an executable file. Return Value The full pathname of the executable executableName in the receiver’s bundle. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 153Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 2.0 and later. Declared in NSBundle.h pathForResource:ofType: Returns the full pathname for the resource identified by the specified name and file extension. - (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension Parameters name The name of the resource file. extension If extension is an empty string or nil, the extension is assumed not to exist and the file is the first file encountered that exactly matches name. Return Value The full pathname for the resource file or nil if the file could not be located. Discussion The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics. The following code fragment gets the path to a plist within the bundle, and loads it into an NSDictionary. NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; if (commonDictionaryPath = [thisBundle pathForResource:@"CommonDictionary" ofType:@"plist"]) { NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 154theDictionary = [[NSDictionary alloc] initWithContentsOfFile:commonDictionaryPath]; // when completed, it is the developer's responsibility to release theDictionary } Availability Available in iOS 2.0 and later. See Also – URLForResource:withExtension: (page 167) Related Sample Code iPhoneMultichannelMixerTest oalTouch PhotoScroller PVRTextureLoader QuartzDemo Declared in NSBundle.h pathForResource:ofType:inDirectory: Returns the full pathname for the resource identified by the specified name and file extension and located in the specified bundle subdirectory. - (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension inDirectory:(NSString *)subpath Parameters name The name of the resource file. extension If extension is an empty string or nil, all the files in subpath and its subdirectories are returned. If an extension is provided the subdirectories are not searched. subpath The name of the bundle subdirectory. Can be nil. Return Value An array of full pathnames for the subpath or nil if no files are located. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 155Discussion If subpath is nil, this method searches the top-level nonlocalized resource directory and the top-level of any language-specific directories. (In Mac OS X, the top-level nonlocalized resource directory is typically called Resources but in iOS, it is the main bundle directory.) For example, suppose you have a Mac OS X application with a modern bundle and you specify @"Documentation" for the subpath parameter. This method would first look in the Contents/Resources/Documentation directory of the bundle, followed by the Documentation subdirectories of each language-specific .lproj directory. Whether this method recurses through subdirectories is dependent on the extension parameter. If nil or an empty string it will recurse, otherwise, it does not. (The search order for the language-specific directories corresponds to the user’s preferences.) For more details see Internationalization Programming Topics. Availability Available in iOS 2.0 and later. See Also – localizedStringForKey:value:table: (page 151) – pathForResource:ofType: (page 154) – pathsForResourcesOfType:inDirectory: (page 157) + pathForResource:ofType:inDirectory: (page 136) Declared in NSBundle.h pathForResource:ofType:inDirectory:forLocalization: Returns the full pathname for the resource identified by the specified name and file extension, located in the specifiedbundlesubdirectory,andlimitedtoglobalresourcesandthoseassociatedwiththespecifiedlocalization. - (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension inDirectory:(NSString *)subpath forLocalization:(NSString *)localizationName Parameters name The name of the resource file. extension If extension is an empty string or nil, the extension is assumed not to exist and the file is the first file encountered that exactly matches name. subpath The name of the bundle subdirectory to search. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 156localizationName The name of the localization. This parameter should correspond to the name of one of the bundle's language-specific resource directories without the .lproj extension. Return Value The full pathname for the resource file or nil if the file could not be located. Discussion This method is equivalent to pathForResource:ofType:inDirectory: (page 155), except that only nonlocalized resources and those in the language-specific .lproj directory specified by localizationName are searched. There should typically be little reason to use this method—see “Getting the Current Language and Locale”. See also preferredLocalizationsFromArray:forPreferences: (page 139) for how to determine what localizations are available. Availability Available in iOS 2.0 and later. Declared in NSBundle.h pathsForResourcesOfType:inDirectory: Returns an array containing the pathnames for all bundle resources having the specified filename extension and residing in the resource subdirectory. - (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)subpath Parameters extension The file extension. If extension is an empty string or nil, the extension is assumed not to exist, all the files in subpath are returned. subpath The name of the bundle subdirectory to search. Return Value An array containing the full pathnames for all bundle resources matching the specified criteria. This method returns an empty array of no matching resource files are found. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 157Discussion This method provides a means for dynamically discovering multiple bundle resources of the same type. If extension is an empty string or nil, all bundle resources in the specified resource directory are returned. The argument subpath specifies the name of a specific subdirectory to search within the current bundle’s resource directory hierarchy. If subpath is nil, this method searches the top-level nonlocalized resource directory and the top-level of any language-specific directories. (In Mac OS X, the top-level nonlocalized resource directory is typically called Resources but in iOS, it is the main bundle directory.) For example, suppose you have a Mac OS X application with a modern bundle and you specify @"Documentation" for the subpath parameter. This method would first look in the Contents/Resources/Documentation directory of the bundle, followed by the Documentation subdirectories of each language-specific .lproj directory. (The search order for the language-specific directories corresponds to the user’s preferences.) This method does not recurse through any other subdirectories at any of these locations. For more details see Internationalization Programming Topics. Availability Available in iOS 2.0 and later. See Also – localizedStringForKey:value:table: (page 151) – pathForResource:ofType: (page 154) – pathForResource:ofType:inDirectory: (page 155) + pathForResource:ofType:inDirectory: (page 136) + pathsForResourcesOfType:inDirectory: (page 137) Declared in NSBundle.h pathsForResourcesOfType:inDirectory:forLocalization: Returns an array containing the file for all bundle resources having the specified filename extension, residing in the specified resource subdirectory, and limited to global resources and those associated with the specified localization. - (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)subpath forLocalization:(NSString *)localizationName Parameters extension The file extension of the files to retrieve. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 158subpath The name of the bundle subdirectory to search. localizationName The name of the localization. This parameter should correspond to the name of one of the bundle's language-specific resource directories without the .lproj extension. Return Value An array containing the full pathnames for all bundle resources matching the specified criteria. This method returns an empty array of no matching resource files are found. Discussion This method is equivalent to pathsForResourcesOfType:inDirectory: (page 157), except that only nonlocalized resources and those in the language-specific .lproj directory specified by localizationName are searched. Availability Available in iOS 2.0 and later. Declared in NSBundle.h preferredLocalizations Returns an array of strings indicating the actual localizations contained in the receiver’s bundle. - (NSArray *)preferredLocalizations Return Value An array of NSString objects, each of which identifies the a localization in the receiver’s bundle. The languages are in the preferred order. Availability Available in iOS 2.0 and later. See Also + preferredLocalizationsFromArray: (page 138) – localizations (page 150) Declared in NSBundle.h NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 159preflightAndReturnError: Returns a Boolean value indicating whether the bundle’s executable code could be loaded successfully. - (BOOL)preflightAndReturnError:(NSError **)error Parameters error On input, a pointer to an error object variable. On output, this variable may contain an error object indicating why the bundle’s executable could not be loaded. If no error would occur, this parameter is left unmodified. You may specify nil for this parameter if you are not interested in the error information. Return Value YES if the bundle’s executable code could be loaded successfully or is already loaded; otherwise, NO if the code could not be loaded. Discussion This method does not actually load the bundle’s executable code. Instead, it performs several checks to see if the code could be loaded and with one exception returns the same errors that would occur during an actual load operation. The one exception is the NSExecutableLinkError error, which requires the actual loading of the code to verify link errors. For a list of possible load errors, see the discussion for the loadAndReturnError: (page 149) method. Availability Available in iOS 2.0 and later. See Also – loadAndReturnError: (page 149) Declared in NSBundle.h principalClass Returns the receiver’s principal class. - (Class)principalClass Return Value The receiver’s principal class—after ensuring that the code containing the definition of that class is dynamically loaded. If the receiver encounters errors in loading or if it can’t find the executable code file in the bundle directory, returns nil. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 160Discussion The principal class typically controls all the other classes in the bundle; it should mediate between those classes and classes external to the bundle. Classes (and categories) are loaded from just one file within the bundle directory. NSBundle obtains the name of the code file to load from the dictionary returned from infoDictionary (page 146), using “NSExecutable” as the key. The bundle determines its principal class in one of two ways: ● It first looks in its own information dictionary, which extracts the information encoded in the bundle’s property list (Info.plist). NSBundle obtains the principal class from the dictionary using the key NSPrincipalClass. For non-loadable bundles (applications and frameworks), if the principal class is not specified in the property list, the method returns nil. ● If the principal class is not specified in the information dictionary, NSBundle identifies the first class loaded as the principal class. When several classes are linked into a dynamically loadable file, the default principal class is the first one listed on the ld command line. In the following example, Reporter would be the principal class: ld -o myBundle -r Reporter.o NotePad.o QueryList.o The order of classes in Xcode’s project browser is the order in which they will be linked. To designate the principal class, control-drag the file containing its implementation to the top of the list. As a side effect of code loading, the receiver posts NSBundleDidLoadNotification (page 173) after all classes and categories have been loaded; see “Notifications” (page 173) for details. The following method obtains a bundle by specifying its path (bundleWithPath: (page 134)), then loads the bundle with principalClass (page 160) and uses the returned class object to allocate and initialize an instance of that class: - (void)loadBundle:(id)sender { Class exampleClass; id newInstance; NSString *path = @"/tmp/Projects/BundleExample/BundleExample.bundle"; NSBundle *bundleToLoad = [NSBundle bundleWithPath:path]; if (exampleClass = [bundleToLoad principalClass]) { newInstance = [[exampleClass alloc] init]; [newInstance doSomething]; } NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 161} Availability Available in iOS 2.0 and later. See Also – classNamed: (page 143) – infoDictionary (page 146) – load (page 148) Declared in NSBundle.h privateFrameworksPath Returns the full pathname of the receiver's subdirectory containing private frameworks. - (NSString *)privateFrameworksPath Return Value The full pathname of the receiver's subdirectory containing private frameworks. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 2.0 and later. Declared in NSBundle.h privateFrameworksURL Returns the file URL of the receiver's subdirectory containing private frameworks. - (NSURL *)privateFrameworksURL Return Value The file URL of the receiver's subdirectory containing private frameworks. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 162Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a URL for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 4.0 and later. Declared in NSBundle.h resourcePath Returns the full pathname of the receiving bundle’s subdirectory containing resources. - (NSString *)resourcePath Return Value The full pathname of the receiving bundle’s subdirectory containing resources. Availability Available in iOS 2.0 and later. See Also – bundlePath (page 142) Declared in NSBundle.h resourceURL Returns the file URL of the receiver's subdirectory containing resource files. - (NSURL *)resourceURL Return Value The file URL of the receiver's subdirectory containing resource files. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 4.0 and later. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 163Declared in NSBundle.h sharedFrameworksPath Returns the full pathname of the receiver's subdirectory containing shared frameworks. - (NSString *)sharedFrameworksPath Return Value The full pathname of the receiver's subdirectory containing shared frameworks. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 2.0 and later. Declared in NSBundle.h sharedFrameworksURL Returns the file URL of the receiver's subdirectory containing shared frameworks. - (NSURL *)sharedFrameworksURL Return Value The file URL of the receiver's subdirectory containing shared frameworks. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a URL for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 4.0 and later. Declared in NSBundle.h NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 164sharedSupportPath Returns the full pathname of the receiver's subdirectory containing shared support files. - (NSString *)sharedSupportPath Return Value The full pathname of the receiver's subdirectory containing shared support files. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 2.0 and later. Declared in NSBundle.h sharedSupportURL Returns the file URL of the receiver's subdirectory containing shared support files. - (NSURL *)sharedSupportURL Return Value The file URL of the receiver's subdirectory containing shared support files. Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 4.0 and later. Declared in NSBundle.h unload Unloads the code associated with the receiver. - (BOOL)unload NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 165Return Value YES if the bundle was successfully unloaded or was not already loaded; otherwise, NO if the bundle could not be unloaded. Discussion This method attempts to unload a bundle’s executable code using the underlying dynamic loader (typically dyld). You may use this method to unload plug-in and framework bundles when you no longer need the code they contain. You should use this method to unload bundles that were loaded using the methods of the NSBundle class only. Do not use this method to unload bundles that were originally loaded using the bundle-manipulation functions in Core Foundation. It is the responsibility of the caller to ensure that no in-memory objects or data structures refer to the code being unloaded. For example, if you have an object whose class is defined in a bundle, you must release that object prior to unloading the bundle. Similarly, your code should not attempt to access any symbols defined in an unloaded bundle. Special Considerations Prior to Mac OS X version 10.5, code could not be unloaded once loaded, and this method would always return NO. In Mac OS X version 10.5 and later, you can unload a bundle’s executable code using this method. Availability Available in iOS 2.0 and later. See Also – loadAndReturnError: (page 149) – load (page 148) Declared in NSBundle.h URLForAuxiliaryExecutable: Returns the file URL of the executable with the specified name in the receiver’s bundle. - (NSURL *)URLForAuxiliaryExecutable:(NSString *)executableName Parameters executableName The name of an executable file. Return Value The file URL of the executable executableName in the receiver’s bundle. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 166Discussion This method returns the appropriate path for modern application and framework bundles. This method may not return a URL for non-standard bundle formats or for some older bundle formats. Availability Available in iOS 4.0 and later. Declared in NSBundle.h URLForResource:withExtension: Returns the file URL for the resource identified by the specified name and file extension. - (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension Parameters name The name of the resource file. extension If extension is an empty string or nil, the extension is assumed not to exist and the file URL is the first file encountered that exactly matches name. Return Value The file URL for the resource file or nil if the file could not be located. Discussion If extension is an empty string or nil, the returned pathname is the first one encountered where the file name exactly matches name. The method first looks for a matching resource file in the nonlocalized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics. Availability Available in iOS 4.0 and later. Related Sample Code Audio Mixer (MixerHost) Audio UI Sounds (SysSound) NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 167ZoomingPDFViewer Declared in NSBundle.h URLForResource:withExtension:subdirectory: Returns the file URL for the resource file identified by the specified name and extension and residing in a given bundle directory. - (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath Parameters name The name of a resource file contained in the directory specified by bundleURL. extension If extension is an empty string or nil, the extension is assumed not to exist and the file URL is the first file encountered that exactly matches name. subpath The path of a top-level bundle directory. This must be a valid path. For example, to specify the bundle directory for a Mac OS X application, you might specify the path /Applications/MyApp.app. Return Value The file URL for the resource file or nil if the file could not be located. This method also returns nil if the bundle specified by the bundlePath parameter does not exist or is not a readable directory. Discussion The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics. Availability Available in iOS 4.0 and later. See Also – pathForResource:ofType:inDirectory: (page 155) NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 168Declared in NSBundle.h URLForResource:withExtension:subdirectory:localization: Returns the file URL for the resource identified by the specified name and file extension, located in the specified bundle subdirectory, and limited to global resources and those associated with the specified localization. - (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)extension subdirectory:(NSString *)subpath localization:(NSString *)localizationName Parameters name The name of the resource file. extension If extension is an empty string or nil, the extension is assumed not to exist and the file URL is the first file encountered that exactly matches name. subpath The name of the bundle subdirectory to search. localizationName The name of the localization. This parameter should correspond to the name of one of the bundle's language-specific resource directories without the .lproj extension. Return Value The file URL for the resource file or nil if the file could not be located. Discussion This method is equivalent to URLsForResourcesWithExtension:subdirectory: (page 170), except that only nonlocalized resources and those in the language-specific .lproj directory specified by localizationName are searched. There should typically be little reason to use this method—see “Getting the Current Language and Locale”. See also preferredLocalizationsFromArray:forPreferences: (page 139) for how to determine what localizations are available. Availability Available in iOS 4.0 and later. Declared in NSBundle.h NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 169URLsForResourcesWithExtension:subdirectory: Returns the file URL for the resource identified by the specified name and file extension and located in the specified bundle subdirectory. - (NSArray *)URLsForResourcesWithExtension:(NSString *)extension subdirectory:(NSString *)subpath Parameters extension If extension is an empty string or nil, the extension is assumed not to exist and the file URL is the first file encountered that exactly matches name. subpath The name of the bundle subdirectory. Return Value The file URL for the resource file or nil if the file could not be located. Discussion If subpath is nil, this method searches the top-level non-localized resource directory and the top-level of any language-specific directories. (In Mac OS X, the top-level non-localized resource directory is typically called Resources but in iOS, it is the main bundle directory.) For example, suppose you have a Mac OS X application with a modern bundle and you specify @"Documentation" for the subpath parameter. This method would first look in the Contents/Resources/Documentation directory of the bundle, followed by the Documentation subdirectories of each language-specific .lproj directory. (The search order for the language-specific directories corresponds to the user’s preferences.) This method does not recurse through any other subdirectories at any of these locations. For more details see Internationalization Programming Topics. Availability Available in iOS 4.0 and later. Declared in NSBundle.h URLsForResourcesWithExtension:subdirectory:localization: Returns an array containing the file URLs for all bundle resources having the specified filename extension, residing in the specified resource subdirectory, and limited to global resources and those associated with the specified localization. NSBundle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 170- (NSArray *)URLsForResourcesWithExtension:(NSString *)extensions subdirectory:(NSString *)subpath localization:(NSString *)localizationName Parameters ext The file extension of the files to retrieve. subpath The name of the bundle subdirectory to search. localizationName The name of the localization. This parameter should correspond to the name of one of the bundle's language-specific resource directories without the .lproj extension. Return Value An array containing the file URLs for all bundle resources matching the specified criteria. This method returns an empty array of no matching resource files are found. Discussion This method is equivalent to URLsForResourcesWithExtension:subdirectory: (page 170), except that only nonlocalized resources and those in the language-specific .lproj directory specified by localizationName are searched. Availability Available in iOS 4.0 and later. Declared in NSBundle.h Constants Mach-O Architecture These constants describe the CPU types that a bundle’s executable code may support. NSBundle Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 171enum { NSBundleExecutableArchitectureI386 = 0x00000007, NSBundleExecutableArchitecturePPC = 0x00000012, NSBundleExecutableArchitectureX86_64 = 0x01000007, NSBundleExecutableArchitecturePPC64 = 0x01000012 }; Constants NSBundleExecutableArchitectureI386 Specifies the 32-bit Intel architecture. Available in iOS 2.0 and later. Declared in NSBundle.h. NSBundleExecutableArchitecturePPC Specifies the 32-bit PowerPC architecture. Available in iOS 2.0 and later. Declared in NSBundle.h. NSBundleExecutableArchitectureX86_64 Specifies the 64-bit Intel architecture. Available in iOS 2.0 and later. Declared in NSBundle.h. NSBundleExecutableArchitecturePPC64 Specifies the 64-bit PowerPC architecture. Available in iOS 2.0 and later. Declared in NSBundle.h. NSLoadedClasses ThisconstantisprovidedintheuserInfo (page 1076)dictionaryoftheNSBundleDidLoadNotification (page 173) notification. NSString * const NSLoadedClasses; Constants NSLoadedClasses An NSArray object containing the names (as NSString objects) of each class that was loaded Available in iOS 2.0 and later. Declared in NSBundle.h. NSBundle Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 172Notifications NSBundleDidLoadNotification NSBundle posts NSBundleDidLoadNotification to notify observers which classes and categories have been dynamically loaded. When a request is made to an NSBundle object for a class (classNamed: (page 143) or principalClass (page 160)), the bundle dynamically loads the executable code file that contains the class implementation and all other class definitions contained in the file. After the module is loaded, the bundle posts the NSBundleDidLoadNotification. The notification object is the NSBundle instance that dynamically loads classes. The userInfo dictionary contains an NSLoadedClasses (page 172) key. In a typical use of this notification, an object might want to enumerate the userInfo array to check if each loaded class conformed to a certain protocol (say, an protocol for a plug-and-play tool set); if a class does conform, the object would create an instance of that class and add the instance to another NSArray object. Availability Available in iOS 2.0 and later. Declared in NSBundle.h NSBundle Class Reference Notifications 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 173Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 4.0 and later. Declared in NSCache.h Overview An NSCache object is a collection-like container, or cache, that stores key-value pairs, similar to the NSDictionary class. Developers often incorporate caches to temporarily store objects with transient data that are expensive to create. Reusing these objects can provide performance benefits, because their values do not have to be recalculated. However, the objects are not critical to the application and can be discarded if memory is tight. If discarded, their values will have to be recomputed again when needed. While a key-value pair is in the cache, the cache maintains a strong reference to it if garbage collection is in effect; in memory-managed code, the cache retains the item. A common data type stored in NSCache objects is an object that implements the NSDiscardableContent protocol. Storing this type of object in a cache has benefits, because its content can be discarded when it is not needed anymore, thus saving memory. By default, NSDiscardableContent objects in the cache are automatically removed from the cache if their content is discarded, although this automatic removal policy can be changed. If an NSDiscardableContent object is put into the cache, the cache calls discardContentIfPossible on it upon its removal. NSCache objects differ from other mutable collections in a few ways: ● The NSCache class incorporates various auto-removal policies, which ensure that it does not use too much of the system’s memory. The system automatically carries out these policies if memory is needed by other applications. When invoked, these policies remove some items from the cache, minimizing its memory footprint. ● You can add, remove, and query items in the cache from different threads without having to lock the cache yourself. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 174 NSCache Class Reference ● Retrieving something from an NSCache object returns an autoreleased result. ● Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it. These features are necessary for the NSCache class, as the cache may decide to automatically mutate itself asynchronously behind the scenes if it is called to free up memory. Tasks Modifying the Cache Name – name (page 178) Returns the name of the cache. – setName: (page 181) Sets the cache’s name attribute to a specific string. Getting a Cached Value – objectForKey: (page 178) Returns the value associated with a given key. Adding and Removing Cached Values – setObject:forKey: (page 182) Sets the value of the specified key in the cache. – setObject:forKey:cost: (page 182) Sets the value of the specified key in the cache, and associates the key-value pair with the specified cost. – removeObjectForKey: (page 179) Removes the value of the specified key in the cache. – removeAllObjects (page 179) Empties the cache. NSCache Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 175Managing Cache Size – countLimit (page 176) Returns the maximum number of objects that the cache can currently hold. – setCountLimit: (page 180) Sets the maximum number of objects that the cache can hold. – totalCostLimit (page 184) Returns the maximum total cost that the cache can have before it starts evicting objects. – setTotalCostLimit: (page 183) Sets the maximum total cost that the cache can have before it starts evicting objects. Managing Discardable Content – evictsObjectsWithDiscardedContent (page 177) Returns whether or not the cache will automatically evict discardable-content objects whose content has been discarded. – setEvictsObjectsWithDiscardedContent: (page 181) Sets whether the cache will automatically evict NSDiscardableContent objects after the object’s content has been discarded. Managing the Delegate – delegate (page 177) Returns the cache’s delegate. – setDelegate: (page 180) Makes the given object the cache’s delegate. Instance Methods countLimit Returns the maximum number of objects that the cache can currently hold. - (NSUInteger)countLimit NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 176Return Value The maximum number of objects that the cache can currently hold. Discussion By default, countLimit will be set to 0. Any countLimit less than or equal to 0 has no effect on the number of allowed entries in the cache. This limit is not a strict limit, and if the cache goes over the limit, an object in the cache could be evicted instantly, later, or possibly never, all depending on the implementation details of the cache. Availability Available in iOS 4.0 and later. See Also – setCountLimit: (page 180) Declared in NSCache.h delegate Returns the cache’s delegate. - (id)delegate Return Value The application delegate object. Discussion The delegate object is expected to conform to the NSCacheDelegate protocol. Availability Available in iOS 4.0 and later. See Also – setDelegate: (page 180) Declared in NSCache.h evictsObjectsWithDiscardedContent Returns whether or not the cache will automatically evict discardable-content objects whose content has been discarded. NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 177- (BOOL)evictsObjectsWithDiscardedContent Return Value YES if the cache will evict the object after it is discarded; otherwise, NO. Discussion By default, evictsObjectsWithDiscardedContent is set to YES. Availability Available in iOS 4.0 and later. See Also – setEvictsObjectsWithDiscardedContent: (page 181) Declared in NSCache.h name Returns the name of the cache. - (NSString *)name Return Value The name of the cache. Discussion Returns the empty string if no name is specified. Availability Available in iOS 4.0 and later. See Also – setName: (page 181) Declared in NSCache.h objectForKey: Returns the value associated with a given key. - (id)objectForKey:(id)key NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 178Parameters key An object identifying the value. Return Value The value associated with key, or NULL if no value is associated with key. The caller does not have to release the value returned to it. Availability Available in iOS 4.0 and later. See Also – setObject:forKey: (page 182) – setObject:forKey:cost: (page 182) – removeObjectForKey: (page 179) Declared in NSCache.h removeAllObjects Empties the cache. - (void)removeAllObjects Availability Available in iOS 4.0 and later. See Also – removeObjectForKey: (page 179) Declared in NSCache.h removeObjectForKey: Removes the value of the specified key in the cache. - (void)removeObjectForKey:(id)key Parameters key The key identifying the value to be removed. NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 179Availability Available in iOS 4.0 and later. See Also – removeAllObjects (page 179) Declared in NSCache.h setCountLimit: Sets the maximum number of objects that the cache can hold. - (void)setCountLimit:(NSUInteger)lim Parameters lim The maximum number of objects that the cache will be allowed to hold. Discussion Setting the count limit to a number less than or equal to 0 will have no effect on the maximum size of the cache. Availability Available in iOS 4.0 and later. See Also – countLimit (page 176) Declared in NSCache.h setDelegate: Makes the given object the cache’s delegate. - (void)setDelegate:(id)del Parameters del The object to be registered as the delegate. NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 180Discussion The delegate object is expected to conform to the NSCacheDelegate protocol. Availability Available in iOS 4.0 and later. See Also – delegate (page 177) Declared in NSCache.h setEvictsObjectsWithDiscardedContent: Sets whether the cache will automatically evict NSDiscardableContent objects after the object’s content has been discarded. - (void)setEvictsObjectsWithDiscardedContent:(BOOL)b Parameters b If YES, the cache evicts NSDiscardableContent objects after the object’s contents has been discarded; if NO the cache does not evict these objects. Availability Available in iOS 4.0 and later. See Also – evictsObjectsWithDiscardedContent (page 177) Declared in NSCache.h setName: Sets the cache’s name attribute to a specific string. - (void)setName:(NSString *)cacheName Parameters cacheName The new name for the cache. NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 181Availability Available in iOS 4.0 and later. See Also – name (page 178) Declared in NSCache.h setObject:forKey: Sets the value of the specified key in the cache. - (void)setObject:(id)obj forKey:(id)key Parameters obj The object to be stored in the cache. key The key with which to associate the value. Discussion Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it. Availability Available in iOS 4.0 and later. See Also – setObject:forKey:cost: (page 182) Declared in NSCache.h setObject:forKey:cost: Sets the value of the specified key in the cache, and associates the key-value pair with the specified cost. - (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)num Parameters obj The object to store in the cache. NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 182key The key with which to associate the value. num The cost with which to associate the key-value pair. Discussion The cost value is used to compute a sum encompassing the costs of all the objects in the cache. When memory is limited or when the total cost of the cache eclipses the maximum allowed total cost, the cache could begin an eviction process to remove some of its elements. However, this eviction process is not in a guaranteed order. As a consequence, if you try to manipulate the cost values to achieve some specific behavior, the consequences could be detrimental to your program. Typically, the obvious cost is the size of the value in bytes. If that information is not readily available, you should not go through the trouble of trying to compute it, as doing so will drive up the cost of using the cache. Pass in 0 for the cost value if you otherwise have nothing useful to pass, or simply use the setObject:forKey: method, which does not require a cost value to be passed in. Unlike an NSMutableDictionary object, a cache does not copy the key objects that are put into it. Availability Available in iOS 4.0 and later. See Also – setObject:forKey: (page 182) – setTotalCostLimit: (page 183) – totalCostLimit (page 184) Declared in NSCache.h setTotalCostLimit: Sets the maximum total cost that the cache can have before it starts evicting objects. - (void)setTotalCostLimit:(NSUInteger)lim Parameters lim The maximum total cost that the cache can have before it starts evicting objects. Availability Available in iOS 4.0 and later. NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 183See Also – totalCostLimit (page 184) Declared in NSCache.h totalCostLimit Returns the maximum total cost that the cache can have before it starts evicting objects. - (NSUInteger)totalCostLimit Return Value The current maximum cost that the cache can have before it starts evicting objects. Discussion The default value is 0, which means there is no limit on the size of the cache. If you add an object to the cache, you may pass in a specified cost for the object, such as the size in bytes of the object. If adding this object to the cache causes the cache’s total cost to rise above totalCostLimit, the cache could automatically evict some of its objects until its total cost falls below totalCostLimit. The order in which the cache evicts objects is not guaranteed. This limit is not a strict limit, and if the cache goes over the limit, an object in the cache could be evicted instantly, at a later point in time, or possibly never, all depending on the implementation details of the cache. Availability Available in iOS 4.0 and later. See Also – setTotalCostLimit: (page 183) – setObject:forKey:cost: (page 182) Declared in NSCache.h NSCache Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 184Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Declared in Foundation/NSURLCache.h Availability Available in iOS 2.0 and later. Companion guide URL Loading System Programming Guide Related sample code URLCache XMLPerformance Overview An NSCachedURLResponse object encapsulates an NSURLResponse object, an NSData object containing the content corresponding to the response, and an NSDictionary containing application specific information. The NSURLCache system stores and retrieves instances of NSCachedURLResponse. Tasks Creating a Cached URL Response – initWithResponse:data: (page 186) Initializes an NSCachedURLResponse object. – initWithResponse:data:userInfo:storagePolicy: (page 187) Initializes an NSCachedURLResponse object. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 185 NSCachedURLResponse Class ReferenceGetting Cached URL Response Properties – data (page 186) Returns the receiver’s cached data. – response (page 188) Returns the NSURLResponse object associated with the receiver. – storagePolicy (page 188) Returns the receiver’s cache storage policy. – userInfo (page 188) Returns the receiver’s user info dictionary. Instance Methods data Returns the receiver’s cached data. - (NSData *)data Return Value The receiver’s cached data. Availability Available in iOS 2.0 and later. Declared in NSURLCache.h initWithResponse:data: Initializes an NSCachedURLResponse object. - (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data Parameters response The response to cache. NSCachedURLResponse Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 186data The data to cache. Return Value The NSCachedURLResponse object, initialized using the given data. Discussion The cache storage policy is set to the default, NSURLCacheStorageAllowed, and the user info dictionary is set to nil. Availability Available in iOS 2.0 and later. See Also – initWithResponse:data:userInfo:storagePolicy: (page 187) Declared in NSURLCache.h initWithResponse:data:userInfo:storagePolicy: Initializes an NSCachedURLResponse object. - (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data userInfo:(NSDictionary *)userInfo storagePolicy:(NSURLCacheStoragePolicy)storagePolicy Parameters response The response to cache. data The data to cache. userInfo An optional dictionary of user information. May be nil. storagePolicy The storage policy for the cached response. Return Value The NSCachedURLResponse object, initialized using the given data. Availability Available in iOS 2.0 and later. NSCachedURLResponse Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 187See Also – initWithResponse:data: (page 186) Declared in NSURLCache.h response Returns the NSURLResponse object associated with the receiver. - (NSURLResponse *)response Return Value The NSURLResponse object associated with the receiver. Availability Available in iOS 2.0 and later. Declared in NSURLCache.h storagePolicy Returns the receiver’s cache storage policy. - (NSURLCacheStoragePolicy)storagePolicy Return Value The receiver’s cache storage policy. Availability Available in iOS 2.0 and later. Declared in NSURLCache.h userInfo Returns the receiver’s user info dictionary. - (NSDictionary *)userInfo NSCachedURLResponse Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 188Return Value An NSDictionary object containing the receiver’s user info, or nil if there is no such object. Availability Available in iOS 2.0 and later. Declared in NSURLCache.h Constants NSURLCacheStoragePolicy These constants specify the caching strategy used by an NSCachedURLResponse object. typedef enum { NSURLCacheStorageAllowed, NSURLCacheStorageAllowedInMemoryOnly, NSURLCacheStorageNotAllowed, } NSURLCacheStoragePolicy; Constants NSURLCacheStorageAllowed Specifies that storage in NSURLCache is allowed without restriction. Important iOS ignores this cache policy, and instead treats it as NSURLCacheStorageAllowedInMemoryOnly. Available in iOS 2.0 and later. Declared in NSURLCache.h. NSURLCacheStorageAllowedInMemoryOnly Specifies that storage in NSURLCache is allowed; however storage should be restricted to memory only. Available in iOS 2.0 and later. Declared in NSURLCache.h. NSURLCacheStorageNotAllowed Specifies that storage in NSURLCache is not allowed in any fashion, either in memory or on disk. Available in iOS 2.0 and later. Declared in NSURLCache.h. NSCachedURLResponse Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 189Availability Available in iOS 2.0 and later. Declared in NSURLCache.h NSCachedURLResponse Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 190Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSCalendar.h Companion guides Date and Time Programming Guide Data Formatting Guide Related sample code Birthdays DateSectionTitles TableViewSuite Overview Calendars encapsulate information about systems of reckoning time in which the beginning, length, and divisions of a year are defined. They provide information about the calendar and support for calendrical computations such as determining the range of a given calendrical unit and adding units to a given absolute time. In a calendar, day, week, weekday, month, and year numbers are generally 1-based, but there may be calendar-specific exceptions. Ordinal numbers, where they occur, are 1-based. Some calendars represented by this API may have to map their basic unit concepts into year/month/week/day/… nomenclature. For example, a calendar composed of 4 quarters in a year instead of 12 months uses the month unit to represent quarters. The particular values of the unit are defined by each calendar, and are not necessarily consistent with values for that unit in another calendar. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 191 NSCalendar Class ReferenceTo do calendar arithmetic, you use NSDate objects in conjunction with a calendar. For example, to convert between a decomposed date in one calendar and another calendar, you must first convert the decomposed elements into a date using the first calendar, then decompose it using the second. NSDate provides the absolute scale and epoch (reference point) for dates and times, which can then be rendered into a particular calendar, for calendrical computations or user display. Two NSCalendar methods that return a date object, dateFromComponents: (page 200), dateByAddingComponents:toDate:options: (page 198), take as a parameter an NSDateComponents object that describes the calendrical components required for the computation. You can provide as many components as you need (or choose to). When there is incomplete information to compute an absolute time, default values similar to 0 and 1 are usually chosen by a calendar, but this is a calendar-specific choice. If you provide inconsistent information, calendar-specific disambiguation is performed (which may involve ignoring one or more of the parameters). Related methods (components:fromDate: (page 196) and components:fromDate:toDate:options: (page 197)) take a bit mask parameter that specifies which components to calculate when returning an NSDateComponents object. The bit mask is composed of NSCalendarUnit constants (see “Constants” (page 209)). NSCalendar is “toll-free bridged” with its Core Foundation counterpart, CFCalendarRef. See “Toll-Free Bridging” for more information on toll-free bridging. Tasks System Locale Information + currentCalendar (page 195) Returns the logical calendar for the current user. + autoupdatingCurrentCalendar (page 194) Returns the current logical calendar for the current user. Initializing a Calendar – initWithCalendarIdentifier: (page 201) Initializes a newly-allocated NSCalendar object for the calendar specified by a given identifier. – setFirstWeekday: (page 206) Sets the index of the first weekday for the receiver. NSCalendar Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 192– setLocale: (page 207) Sets the locale for the receiver. – setMinimumDaysInFirstWeek: (page 207) Sets the minimum number of days in the first week of the receiver. – setTimeZone: (page 208) Sets the time zone for the receiver. Getting Information About a Calendar – calendarIdentifier (page 195) Returns the identifier for the receiver. – firstWeekday (page 201) Returns the index of the first weekday of the receiver. – locale (page 202) Returns the locale for the receiver. – maximumRangeOfUnit: (page 202) The maximum range limits of the values that a given unit can take on in the receive – minimumDaysInFirstWeek (page 203) Returns the minimum number of days in the first week of the receiver. – minimumRangeOfUnit: (page 203) Returns the minimum range limits of the values that a given unit can take on in the receiver. – ordinalityOfUnit:inUnit:forDate: (page 204) Returns, for a given absolute time, the ordinal number of a smaller calendar unit (such as a day) within a specified larger calendar unit (such as a week). – rangeOfUnit:inUnit:forDate: (page 205) Returns the range of absolute time values that a smaller calendar unit (such as a day) can take on in a larger calendar unit (such as a month) that includes a specified absolute time. – rangeOfUnit:startDate:interval:forDate: (page 206) Returns by reference the starting time and duration of a given calendar unit that contains a given date. – timeZone (page 208) Returns the time zone for the receiver. NSCalendar Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 193Calendrical Calculations – components:fromDate: (page 196) Returns a NSDateComponents object containing a given date decomposed into specified components. – components:fromDate:toDate:options: (page 197) Returns, as an NSDateComponents object using specified components, the difference between two supplied dates. – dateByAddingComponents:toDate:options: (page 198) Returns a new NSDate object representing the absolute time calculated by adding given components to a given date. – dateFromComponents: (page 200) Returns a new NSDate object representing the absolute time calculated from given components. Class Methods autoupdatingCurrentCalendar Returns the current logical calendar for the current user. + (id)autoupdatingCurrentCalendar Return Value The current logical calendar for the current user. Discussion Settings you get from this calendar do change as the user’s settings change (contrast with currentCalendar (page 195)). Note that if you cache values based on the calendar or related information those caches will of course not be automatically updated by the updating of the calendar object. Availability Available in iOS 2.0 and later. See Also + currentCalendar (page 195) – initWithCalendarIdentifier: (page 201) – calendarIdentifier (page 195) NSCalendar Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 194Declared in NSCalendar.h currentCalendar Returns the logical calendar for the current user. + (id)currentCalendar Return Value The logical calendar for the current user. Discussion The returned calendar is formed from the settings for the current user’s chosen system locale overlaid with any custom settings the user has specified in System Preferences. Settings you get from this calendar do not change as System Preferences are changed, so that your operations are consistent (contrast with autoupdatingCurrentCalendar (page 194)). Availability Available in iOS 2.0 and later. See Also + autoupdatingCurrentCalendar (page 194) – initWithCalendarIdentifier: (page 201) – calendarIdentifier (page 195) Related Sample Code DateSectionTitles Declared in NSCalendar.h Instance Methods calendarIdentifier Returns the identifier for the receiver. - (NSString *)calendarIdentifier Return Value The identifier for the receiver. For valid identifiers, see NSLocale. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 195Availability Available in iOS 2.0 and later. See Also + autoupdatingCurrentCalendar (page 194) – initWithCalendarIdentifier: (page 201) Declared in NSCalendar.h components:fromDate: Returns a NSDateComponents object containing a given date decomposed into specified components. - (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date Parameters unitFlags The components into which to decompose date—a bitwise OR of NSCalendarUnit constants. date The date for which to perform the calculation. Return Value An NSDateComponents object containing date decomposed into the components specified by unitFlags. Returns nil if date falls outside of the defined range of the receiver or if the computation cannot be performed Discussion The Weekday ordinality, when requested, refers to the next larger (than Week) of the requested units. Some computations can take a relatively long time. The following example shows how to use this method to determine the current year, month, and day, using an existing calendar (gregorian): unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDate *date = [NSDate date]; NSDateComponents *comps = [gregorian components:unitFlags fromDate:date]; Availability Available in iOS 2.0 and later. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 196See Also – dateFromComponents: (page 200) – components:fromDate:toDate:options: (page 197) – dateByAddingComponents:toDate:options: (page 198) Related Sample Code Birthdays DateSectionTitles Declared in NSCalendar.h components:fromDate:toDate:options: Returns, as an NSDateComponents object using specified components, the difference between two supplied dates. - (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts Parameters unitFlags Specifies the components for the returned NSDateComponents object—a bitwise OR of NSCalendarUnit constants. startingDate The start date for the calculation. resultDate The end date for the calculation. opts Options for the calculation. If you specify a “wrap” option (NSWrapCalendarComponents), the specified components are incremented and wrap around to zero/one on overflow, but do not cause higher units to be incremented. When the wrap option is false, overflow in a unit carries into the higher units, as in typical addition. Return Value An NSDateComponents object whose components are specified by unitFlags and calculated from the difference between the resultDate and startDate using the options specified by opts. Returns nil if either date falls outside the defined range of the receiver or if the computation cannot be performed. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 197Discussion The result is lossy if there is not a small enough unit requested to hold the full precision of the difference. Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days. The resulting component values may be negative if resultDate is before startDate. The following example shows how to get the approximate number of months and days between two dates using an existing calendar (gregorian): NSDate *startDate = ...; NSDate *endDate = ...; unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; int months = [comps month]; int days = [comps day]; Note that some computations can take a relatively long time. Availability Available in iOS 2.0 and later. See Also – dateByAddingComponents:toDate:options: (page 198) – dateFromComponents: (page 200) Declared in NSCalendar.h dateByAddingComponents:toDate:options: Returns a new NSDate object representing the absolute time calculated by adding given components to a given date. - (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts Parameters comps The components to add to date. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 198date The date to which comps are added. opts Options for the calculation. See “NSDateComponents wrapping behavior” (page 212) for possible values. Pass 0 to specify no options. If you specify no options (you pass 0), overflow in a unit carries into the higher units (as in typical addition). Return Value A new NSDate object representing the absolute time calculated by adding to date the calendrical components specified by comps using the options specified by opts. Returns nil if date falls outside the defined range of the receiver or if the computation cannot be performed. Discussion Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally components are added in the order specified. The following example shows how to add 2 months and 3 days to the current date and time using an existing calendar (gregorian): NSDate *currentDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setMonth:2]; [comps setDay:3]; NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0]; [comps release]; Note that some computations can take a relatively long time. Availability Available in iOS 2.0 and later. See Also – dateFromComponents: (page 200) – components:fromDate:toDate:options: (page 197) Declared in NSCalendar.h NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 199dateFromComponents: Returns a new NSDate object representing the absolute time calculated from given components. - (NSDate *)dateFromComponents:(NSDateComponents *)comps Parameters comps The components from which to calculate the returned date. Return Value A new NSDate object representing the absolute time calculated from comps. Returns nil if the receiver cannot convert the components given in comps into an absolute time. The method also returns nil and for out-of-range values. Discussion When there are insufficient components provided to completely specify an absolute time, a calendar uses default values of its choice. When there is inconsistent information, a calendar may ignore some of the components parameters or the method may return nil. Unnecessary components are ignored (for example, Day takes precedence over Weekday and Weekday ordinals). The following example shows how to use this method to create a date object to represent 14:10:00 on 6 January 1965, for a given calendar (gregorian). NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setYear:1965]; [comps setMonth:1]; [comps setDay:6]; [comps setHour:14]; [comps setMinute:10]; [comps setSecond:0]; NSDate *date = [gregorian dateFromComponents:comps]; [comps release]; Note that some computations can take a relatively long time to perform. Availability Available in iOS 2.0 and later. See Also – components:fromDate: (page 196) NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 200– dateFromComponents: (page 200) Related Sample Code DateSectionTitles Declared in NSCalendar.h firstWeekday Returns the index of the first weekday of the receiver. - (NSUInteger)firstWeekday Return Value The index of the first weekday of the receiver. Availability Available in iOS 2.0 and later. See Also – setFirstWeekday: (page 206) Declared in NSCalendar.h initWithCalendarIdentifier: Initializes a newly-allocated NSCalendar object for the calendar specified by a given identifier. - (id)initWithCalendarIdentifier:(NSString *)string Parameters string The identifier for the new calendar. For valid identifiers, see NSLocale. Return Value The initialized calendar, or nil if the identifier is unknown (if, for example, it is either an unrecognized string or the calendar is not supported by the current version of the operating system). Availability Available in iOS 2.0 and later. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 201See Also + autoupdatingCurrentCalendar (page 194) – calendarIdentifier (page 195) Related Sample Code Birthdays TableViewSuite Declared in NSCalendar.h locale Returns the locale for the receiver. - (NSLocale *)locale Return Value The locale for the receiver. Availability Available in iOS 2.0 and later. See Also – setLocale: (page 207) Declared in NSCalendar.h maximumRangeOfUnit: The maximum range limits of the values that a given unit can take on in the receive - (NSRange)maximumRangeOfUnit:(NSCalendarUnit)unit Parameters unit The unit for which the maximum range is returned. Return Value The maximum range limits of the values that the unit specified by unit can take on in the receiver. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 202Discussion As an example, in the Gregorian calendar the maximum range of values for the Day unit is 1-31. Availability Available in iOS 2.0 and later. See Also – minimumRangeOfUnit: (page 203) Declared in NSCalendar.h minimumDaysInFirstWeek Returns the minimum number of days in the first week of the receiver. - (NSUInteger)minimumDaysInFirstWeek Return Value The minimum number of days in the first week of the receiver Availability Available in iOS 2.0 and later. See Also – setMinimumDaysInFirstWeek: (page 207) Declared in NSCalendar.h minimumRangeOfUnit: Returns the minimum range limits of the values that a given unit can take on in the receiver. - (NSRange)minimumRangeOfUnit:(NSCalendarUnit)unit Parameters unit The unit for which the maximum range is returned. Return Value The minimum range limits of the values that the unit specified by unit can take on in the receiver. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 203Discussion As an example, in the Gregorian calendar the minimum range of values for the Day unit is 1-28. Availability Available in iOS 2.0 and later. See Also – maximumRangeOfUnit: (page 202) Declared in NSCalendar.h ordinalityOfUnit:inUnit:forDate: Returns, for a given absolute time, the ordinal number of a smaller calendar unit (such as a day) within a specified larger calendar unit (such as a week). - (NSUInteger)ordinalityOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date Parameters smaller The smaller calendar unit larger The larger calendar unit date The absolute time for which the calculation is performed Return Value The ordinal number of smaller within larger at the time specified by date. Returns NSNotFound if larger is not logically bigger than smaller in the calendar, or the given combination of units does not make sense (or is a computation which is undefined). Discussion The ordinality is in most cases not the same as the decomposed value of the unit. Typically return values are 1 and greater. For example, the time 00:45 is in the first hour of the day, and for units Hour and Day respectively, the result would be 1. An exception is the week-in-month calculation, which returns 0 for days before the first week in the month containing the date. Note that some computations can take a relatively long time. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 204Availability Available in iOS 2.0 and later. See Also – rangeOfUnit:inUnit:forDate: (page 205) – rangeOfUnit:startDate:interval:forDate: (page 206) Declared in NSCalendar.h rangeOfUnit:inUnit:forDate: Returns the range of absolute time values that a smaller calendar unit (such as a day) can take on in a larger calendar unit (such as a month) that includes a specified absolute time. - (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date Parameters smaller The smaller calendar unit. larger The larger calendar unit. date The absolute time for which the calculation is performed. Return Value The range of absolute time values smaller can take on in larger at the time specified by date. Returns {NSNotFound, NSNotFound} if larger is not logically bigger than smaller in the calendar, or the given combination of units does not make sense (or is a computation which is undefined). Discussion You can use this method to calculate, for example, the range the Day unit can take on in the Month in which date lies. Availability Available in iOS 2.0 and later. See Also – rangeOfUnit:startDate:interval:forDate: (page 206) – ordinalityOfUnit:inUnit:forDate: (page 204) NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 205Related Sample Code Birthdays Declared in NSCalendar.h rangeOfUnit:startDate:interval:forDate: Returns by reference the starting time and duration of a given calendar unit that contains a given date. - (BOOL)rangeOfUnit:(NSCalendarUnit)unit startDate:(NSDate **)datep interval:(NSTimeInterval *)tip forDate:(NSDate *)date Parameters unit A calendar unit (see “Calendar Units” (page 209) for possible values). datep Upon return, contains the starting time of the calendar unit unit that contains the date date tip Upon return, contains the duration of the calendar unit unit that contains the date date date A date. Return Value YES if the starting time and duration of a unit could be calculated, otherwise NO. Availability Available in iOS 2.0 and later. See Also – rangeOfUnit:inUnit:forDate: (page 205) – ordinalityOfUnit:inUnit:forDate: (page 204) Declared in NSCalendar.h setFirstWeekday: Sets the index of the first weekday for the receiver. - (void)setFirstWeekday:(NSUInteger)weekday NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 206Parameters weekday The first weekday for the receiver. Availability Available in iOS 2.0 and later. See Also – firstWeekday (page 201) Declared in NSCalendar.h setLocale: Sets the locale for the receiver. - (void)setLocale:(NSLocale *)locale Parameters locale The locale for the receiver. Availability Available in iOS 2.0 and later. See Also – locale (page 202) Declared in NSCalendar.h setMinimumDaysInFirstWeek: Sets the minimum number of days in the first week of the receiver. - (void)setMinimumDaysInFirstWeek:(NSUInteger)mdw Parameters mdw The minimum number of days in the first week of the receiver. NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 207Availability Available in iOS 2.0 and later. See Also – minimumDaysInFirstWeek (page 203) Declared in NSCalendar.h setTimeZone: Sets the time zone for the receiver. - (void)setTimeZone:(NSTimeZone *)tz Parameters tz The time zone for the receiver. Availability Available in iOS 2.0 and later. See Also – timeZone (page 208) Declared in NSCalendar.h timeZone Returns the time zone for the receiver. - (NSTimeZone *)timeZone Return Value The time zone for the receiver. Availability Available in iOS 2.0 and later. See Also – setTimeZone: (page 208) NSCalendar Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 208Declared in NSCalendar.h Constants Calendar Units Specify calendrical units such as day and month. enum { NSEraCalendarUnit = kCFCalendarUnitEra, NSYearCalendarUnit = kCFCalendarUnitYear, NSMonthCalendarUnit = kCFCalendarUnitMonth, NSDayCalendarUnit = kCFCalendarUnitDay, NSHourCalendarUnit = kCFCalendarUnitHour, NSMinuteCalendarUnit = kCFCalendarUnitMinute, NSSecondCalendarUnit = kCFCalendarUnitSecond, NSWeekCalendarUnit = kCFCalendarUnitWeek, NSWeekdayCalendarUnit = kCFCalendarUnitWeekday, NSWeekdayOrdinalCalendarUnit = kCFCalendarUnitWeekdayOrdinal, NSQuarterCalendarUnit = kCFCalendarUnitQuarter, NSWeekOfMonthCalendarUnit = kCFCalendarUnitWeekOfMonth, NSWeekOfYearCalendarUnit = kCFCalendarUnitWeekOfYear, NSYearForWeekOfYearCalendarUnit = kCFCalendarUnitYearForWeekOfYear NSCalendarCalendarUnit = (1 << 20), NSTimeZoneCalendarUnit = (1 << 21), }; typedef NSUInteger NSCalendarUnit; Constants NSEraCalendarUnit Specifies the era unit. The corresponding value is an NSInteger. Equal to kCFCalendarUnitEra. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSYearCalendarUnit Specifies the year unit. The corresponding value is an NSInteger. Equal to kCFCalendarUnitYear. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSCalendar Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 209NSMonthCalendarUnit Specifies the month unit. The corresponding value is an NSInteger. Equal to kCFCalendarUnitMonth. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSDayCalendarUnit Specifies the day unit. The corresponding value is an NSInteger. Equal to kCFCalendarUnitDay. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSHourCalendarUnit Specifies the hour unit. The corresponding value is an NSInteger. Equal to kCFCalendarUnitHour. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSMinuteCalendarUnit Specifies the minute unit. The corresponding value is an NSInteger. Equal to kCFCalendarUnitMinute. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSSecondCalendarUnit Specifies the second unit. The corresponding value is a double. Equal to kCFCalendarUnitSecond. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSWeekCalendarUnit Specifies the week unit. The corresponding value is an kCFCalendarUnitSecond. Equal to kCFCalendarUnitWeek. Available in iOS 2.0 and later. Declared in NSCalendar.h. NSWeekdayCalendarUnit Specifies the weekday unit. The corresponding value is an kCFCalendarUnitSecond. Equal to kCFCalendarUnitWeekday. The weekday units are the numbers 1 through N (where for the Gregorian calendar N=7 and 1 is Sunday). Available in iOS 2.0 and later. Declared in NSCalendar.h. NSCalendar Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 210NSWeekdayOrdinalCalendarUnit Specifies the ordinal weekday unit. The corresponding value is an kCFCalendarUnitSecond. Equal to kCFCalendarUnitWeekdayOrdinal. The weekday ordinal unit describes ordinal position within the month unit of the corresponding weekday unit. For example, in the Gregorian calendar a weekday ordinal unit of 2 for a weekday unit 3 indicates "the second Tuesday in the month". Available in iOS 2.0 and later. Declared in NSCalendar.h. NSQuarterCalendarUnit Specifies the quarter of the calendar as an kCFCalendarUnitSecond. Available in iOS 4.0 and later. Declared in NSCalendar.h. NSWeekOfMonthCalendarUnit Specifies the original week of a month calendar unit. Available in iOS 5.0 and later. Declared in NSCalendar.h. NSWeekOfYearCalendarUnit Specifies the original week of the year calendar unit. Available in iOS 5.0 and later. Declared in NSCalendar.h. NSYearForWeekOfYearCalendarUnit Specifies the year when the calendar is being interpreted as a week-based calendar. Available in iOS 5.0 and later. Declared in NSCalendar.h. NSCalendarCalendarUnit Specifies the calendar of the calendar. Available in iOS 4.0 and later. Declared in NSCalendar.h. NSTimeZoneCalendarUnit Specifies the time zone of the calendar as an NSTimeZone. Available in iOS 4.0 and later. Declared in NSCalendar.h. Discussion Calendar units may be used as a bit mask to specify a combination of units. Values in this enum are equal to the corresponding constants in the CFCalendarUnit enum. NSCalendar Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 211Declared in NSCalendar.h NSDateComponents wrapping behavior The wrapping option specifies wrapping behavior for calculations involving NSDateComponents objects. enum { NSWrapCalendarComponents = kCFCalendarComponentsWrap, }; Constants NSWrapCalendarComponents Specifies that the components specified for an NSDateComponents object should be incremented and wrap around to zero/one on overflow, but should not cause higher units to be incremented. Available in iOS 2.0 and later. Declared in NSCalendar.h. Declared in NSCalendar.h NSCalendar Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 212Inherits from NSObject Conforms to NSCoding NSCopying NSMutableCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSCharacterSet.h Companion guide String Programming Guide Related sample code LazyTableImages SeismicXML SimpleFTPSample SimpleURLConnections Overview An NSCharacterSet object represents a set of Unicode-compliant characters. NSString and NSScanner objects use NSCharacterSet objects to group characters together for searching operations, so that they can find any of a particular set of characters during a search. The cluster’s two public classes, NSCharacterSet and NSMutableCharacterSet, declare the programmatic interface for static and dynamic character sets, respectively. The objects you create using these classes are referred to as character set objects (and when no confusion will result, merely as character sets). Because of the nature of class clusters, character set objects aren’t actual instances of the NSCharacterSet or NSMutableCharacterSet classes but of one of their private subclasses. Although a character set object’s class is private, its interface is public, as declared by these abstract superclasses, NSCharacterSet and NSMutableCharacterSet. The character set classes adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert a character set of one type to the other. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 213 NSCharacterSet Class ReferenceThe NSCharacterSet class declares the programmatic interface for an object that manages a set of Unicode characters (see the NSString class cluster specification for information on Unicode). NSCharacterSet’s principal primitive method, characterIsMember: (page 228), provides the basis for all other instance methods in its interface. A subclass of NSCharacterSet needs only to implement this method, plus mutableCopyWithZone: (page 2103), for proper behavior. For optimal performance, a subclass should also override bitmapRepresentation (page 227), which otherwise works by invoking characterIsMember: (page 228) for every possible Unicode value. NSCharacterSet is “toll-free bridged” with its Cocoa Foundation counterpart, CFCharacterSetRef. See “Toll-Free Bridging” for more information on toll-free bridging. The mutable subclass of NSCharacterSet is NSMutableCharacterSet. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSMutableCopying mutableCopyWithZone: (page 2103) Tasks Creating a Standard Character Set + alphanumericCharacterSet (page 216) Returns a character set containing the characters in the categories Letters, Marks, and Numbers. + capitalizedLetterCharacterSet (page 217) Returns a character set containing the characters in the category of Titlecase Letters. + controlCharacterSet (page 220) Returns a character set containing the characters in the categories of Control or Format Characters. + decimalDigitCharacterSet (page 221) Returns a character set containing the characters in the category of Decimal Numbers. NSCharacterSet Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 214+ decomposableCharacterSet (page 221) Returns a character set containing all individual Unicode characters that can also be represented as composed character sequences. + illegalCharacterSet (page 222) Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard. + letterCharacterSet (page 222) Returns a character set containing the characters in the categories Letters and Marks. + lowercaseLetterCharacterSet (page 223) Returns a character set containing the characters in the category of Lowercase Letters. + newlineCharacterSet (page 223) Returns a character set containing the newline characters. + nonBaseCharacterSet (page 224) Returns a character set containing the characters in the category of Marks. + punctuationCharacterSet (page 224) Returns a character set containing the characters in the category of Punctuation. + symbolCharacterSet (page 225) Returns a character set containing the characters in the category of Symbols. + uppercaseLetterCharacterSet (page 225) Returns a character set containing the characters in the categories of Uppercase Letters and Titlecase Letters. + whitespaceAndNewlineCharacterSet (page 226) Returns a character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085). + whitespaceCharacterSet (page 226) Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009). Creating a Custom Character Set + characterSetWithCharactersInString: (page 218) Returns a character set containing the characters in a given string. + characterSetWithRange: (page 219) Returns a character set containing characters with Unicode values in a given range. – invertedSet (page 229) Returns a character set containing only characters that don’t exist in the receiver. NSCharacterSet Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 215Creating and Managing Character Sets as Bitmap Representations + characterSetWithBitmapRepresentation: (page 217) Returns a character set containing characters determined by a given bitmap representation. + characterSetWithContentsOfFile: (page 219) Returns a character set read from the bitmap representation stored in the file a given path. – bitmapRepresentation (page 227) Returns an NSData object encoding the receiver in binary format. Testing Set Membership – characterIsMember: (page 228) Returns a Boolean value that indicates whether a given character is in the receiver. – hasMemberInPlane: (page 228) Returns a Boolean value that indicates whether the receiver has at least one member in a given character plane. – isSupersetOfSet: (page 229) Returns a Boolean value that indicates whether the receiver is a superset of another given character set. – longCharacterIsMember: (page 229) Returns a Boolean value that indicates whether a given long character is a member of the receiver. Class Methods alphanumericCharacterSet Returns a character set containing the characters in the categories Letters, Marks, and Numbers. + (id)alphanumericCharacterSet Return Value A character set containing the characters in the categories Letters, Marks, and Numbers. Discussion Informally, this set is the set of all characters used as basic units of alphabets, syllabaries, ideographs, and digits. Availability Available in iOS 2.0 and later. NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 216See Also + letterCharacterSet (page 222) + decimalDigitCharacterSet (page 221) Declared in NSCharacterSet.h capitalizedLetterCharacterSet Returns a character set containing the characters in the category of Titlecase Letters. + (id)capitalizedLetterCharacterSet Return Value A character set containing the characters in the category of Titlecase Letters. Availability Available in iOS 2.0 and later. See Also + letterCharacterSet (page 222) + uppercaseLetterCharacterSet (page 225) Declared in NSCharacterSet.h characterSetWithBitmapRepresentation: Returns a character set containing characters determined by a given bitmap representation. + (id)characterSetWithBitmapRepresentation:(NSData *)data Parameters data A bitmap representation of a character set. Return Value A character set containing characters determined by data. Discussion This method is useful for creating a character set object with data from a file or other external data source. NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 217A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To add a character with decimal Unicode value n to a raw bitmap representation, use a statement such as the following: unsigned char bitmapRep[8192]; bitmapRep[n >> 3] |= (((unsigned int)1) << (n & 7)); To remove that character: bitmapRep[n >> 3] &= ~(((unsigned int)1) << (n & 7)); Availability Available in iOS 2.0 and later. See Also – bitmapRepresentation (page 227) + characterSetWithContentsOfFile: (page 219) Declared in NSCharacterSet.h characterSetWithCharactersInString: Returns a character set containing the characters in a given string. + (id)characterSetWithCharactersInString:(NSString *)aString Parameters aString A string containing characters for the new character set. Return Value A character set containing the characters in aString. Returns an empty character set if aString is empty. Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 218characterSetWithContentsOfFile: Returns a character set read from the bitmap representation stored in the file a given path. + (id)characterSetWithContentsOfFile:(NSString *)path Parameters path A path to a file containing a bitmap representation of a character set. The path name must end with the extension .bitmap. Return Value A character set read from the bitmap representation stored in the file at path. Discussion To read a bitmap representation from any file, use the NSData methoddataWithContentsOfFile:options:error: (page 303) and pass the result to characterSetWithBitmapRepresentation: (page 217). This method doesn’t use filenames to check for the uniqueness of the character sets it creates. To prevent duplication of character sets in memory, cache them and make them available through an API that checks whether the requested set has already been loaded. Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h characterSetWithRange: Returns a character set containing characters with Unicode values in a given range. + (id)characterSetWithRange:(NSRange)aRange Parameters aRange A range of Unicode values. aRange.location is the value of the first character to return; aRange.location + aRange.length– 1 is the value of the last. NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 219Return Value A character set containing characters whose Unicode values are given by aRange. If aRange.length is 0, returns an empty character set. Discussion This code excerpt creates a character set object containing the lowercase English alphabetic characters: NSRange lcEnglishRange; NSCharacterSet *lcEnglishLetters; lcEnglishRange.location = (unsigned int)'a'; lcEnglishRange.length = 26; lcEnglishLetters = [NSCharacterSet characterSetWithRange:lcEnglishRange]; Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h controlCharacterSet Returns a character set containing the characters in the categories of Control or Format Characters. + (id)controlCharacterSet Return Value A character set containing the characters in the categories of Control or Format Characters. Discussion These characters are specifically the Unicode values U+0000 to U+001F and U+007F to U+009F. Availability Available in iOS 2.0 and later. See Also + illegalCharacterSet (page 222) Declared in NSCharacterSet.h NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 220decimalDigitCharacterSet Returns a character set containing the characters in the category of Decimal Numbers. + (id)decimalDigitCharacterSet Return Value A character set containing the characters in the category of Decimal Numbers. Discussion Informally, this set is the set of all characters used to represent the decimal values 0 through 9. These characters include, for example, the decimal digits of the Indic scripts and Arabic. Availability Available in iOS 2.0 and later. See Also + alphanumericCharacterSet (page 216) Declared in NSCharacterSet.h decomposableCharacterSet Returns a character set containing all individual Unicode characters that can also be represented as composed character sequences. + (id)decomposableCharacterSet Return Value A character set containing all individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of “standard decomposition” in version 3.2 of the Unicode character encoding standard. Discussion These characters include compatibility characters as well as pre-composed characters. Note This character set doesn’t currently include the Hangul characters defined in version 2.0 of the Unicode standard. Availability Available in iOS 2.0 and later. NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 221See Also + nonBaseCharacterSet (page 224) Declared in NSCharacterSet.h illegalCharacterSet Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard. + (id)illegalCharacterSet Return Value A character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard. Availability Available in iOS 2.0 and later. See Also + controlCharacterSet (page 220) Declared in NSCharacterSet.h letterCharacterSet Returns a character set containing the characters in the categories Letters and Marks. + (id)letterCharacterSet Return Value A character set containing the characters in the categories Letters and Marks. Discussion Informally, this set is the set of all characters used as letters of alphabets and ideographs. Availability Available in iOS 2.0 and later. See Also + alphanumericCharacterSet (page 216) NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 222+ lowercaseLetterCharacterSet (page 223) + uppercaseLetterCharacterSet (page 225) Declared in NSCharacterSet.h lowercaseLetterCharacterSet Returns a character set containing the characters in the category of Lowercase Letters. + (id)lowercaseLetterCharacterSet Return Value A character set containing the characters in the category of Lowercase Letters. Discussion Informally, this set is the set of all characters used as lowercase letters in alphabets that make case distinctions. Availability Available in iOS 2.0 and later. See Also + uppercaseLetterCharacterSet (page 225) + letterCharacterSet (page 222) Declared in NSCharacterSet.h newlineCharacterSet Returns a character set containing the newline characters. + (id)newlineCharacterSet Return Value A character set containing the newline characters (U+000A–U+000D, U+0085). Availability Available in iOS 2.0 and later. See Also + whitespaceAndNewlineCharacterSet (page 226) + whitespaceCharacterSet (page 226) NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 223Declared in NSCharacterSet.h nonBaseCharacterSet Returns a character set containing the characters in the category of Marks. + (id)nonBaseCharacterSet Return Value A character set containing the characters in the category of Marks. Discussion This set is also defined as all legal Unicode characters with a non-spacing priority greater than 0. Informally, this set is the set of all characters used as modifiers of base characters. Availability Available in iOS 2.0 and later. See Also + decomposableCharacterSet (page 221) Declared in NSCharacterSet.h punctuationCharacterSet Returns a character set containing the characters in the category of Punctuation. + (id)punctuationCharacterSet Return Value A character set containing the characters in the category of Punctuation. Discussion Informally, this set is the set of all non-whitespace characters used to separate linguistic units in scripts, such as periods, dashes, parentheses, and so on. Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 224symbolCharacterSet Returns a character set containing the characters in the category of Symbols. + (id)symbolCharacterSet Return Value A character set containing the characters in the category of Symbols. Discussion These characters include, for example, the dollar sign ($) and the plus (+) sign. Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h uppercaseLetterCharacterSet Returns a character set containing the characters in the categories of Uppercase Letters and Titlecase Letters. + (id)uppercaseLetterCharacterSet Return Value A character set containing the characters in the categories of Uppercase Letters and Titlecase Letters. Discussion Informally, this set is the set of all characters used as uppercase letters in alphabets that make case distinctions. Availability Available in iOS 2.0 and later. See Also + capitalizedLetterCharacterSet (page 217) + lowercaseLetterCharacterSet (page 223) + letterCharacterSet (page 222) Declared in NSCharacterSet.h NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 225whitespaceAndNewlineCharacterSet Returns a character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085). + (id)whitespaceAndNewlineCharacterSet Return Value A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085). Availability Available in iOS 2.0 and later. See Also + newlineCharacterSet (page 223) + whitespaceCharacterSet (page 226) Related Sample Code LazyTableImages Declared in NSCharacterSet.h whitespaceCharacterSet Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009). + (id)whitespaceCharacterSet Return Value A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009). Discussion This set doesn’t contain the newline or carriage return characters. Availability Available in iOS 2.0 and later. See Also + whitespaceAndNewlineCharacterSet (page 226) + newlineCharacterSet (page 223) Related Sample Code SimpleFTPSample NSCharacterSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 226SimpleURLConnections Declared in NSCharacterSet.h Instance Methods bitmapRepresentation Returns an NSData object encoding the receiver in binary format. - (NSData *)bitmapRepresentation Return Value An NSData object encoding the receiver in binary format. Discussion This format is suitable for saving to a file or otherwise transmitting or archiving. A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To test for the presence of a character with decimal Unicode value n in a raw bitmap representation, use an expression such as the following: unsigned char bitmapRep[8192]; if (bitmapRep[n >> 3] & (((unsigned int)1) << (n & 7))) { /* Character is present. */ } Availability Available in iOS 2.0 and later. See Also + characterSetWithBitmapRepresentation: (page 217) Declared in NSCharacterSet.h NSCharacterSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 227characterIsMember: Returns a Boolean value that indicates whether a given character is in the receiver. - (BOOL)characterIsMember:(unichar)aCharacter Parameters aCharacter The character to test for membership of the receiver. Return Value YES if aCharacter is in the receiving character set, otherwise NO. Availability Available in iOS 2.0 and later. See Also – longCharacterIsMember: (page 229) Declared in NSCharacterSet.h hasMemberInPlane: Returns a Boolean value that indicates whether the receiver has at least one member in a given character plane. - (BOOL)hasMemberInPlane:(uint8_t)thePlane Parameters thePlane A character plane. Return Value YES if the receiver has at least one member in thePlane, otherwise NO. Discussion This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane is plane 0. Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h NSCharacterSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 228invertedSet Returns a character set containing only characters that don’t exist in the receiver. - (NSCharacterSet *)invertedSet Return Value A character set containing only characters that don’t exist in the receiver. Discussion Inverting an immutable character set is much more efficient than inverting a mutable character set. Availability Available in iOS 2.0 and later. See Also invert (page 971) (NSMutableCharacterSet) Declared in NSCharacterSet.h isSupersetOfSet: Returns a Boolean value that indicates whether the receiver is a superset of another given character set. - (BOOL)isSupersetOfSet:(NSCharacterSet *)theOtherSet Parameters theOtherSet A character set. Return Value YES if the receiver is a superset of theOtherSet, otherwise NO. Availability Available in iOS 2.0 and later. Declared in NSCharacterSet.h longCharacterIsMember: Returns a Boolean value that indicates whether a given long character is a member of the receiver. NSCharacterSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 229- (BOOL)longCharacterIsMember:(UTF32Char)theLongChar Parameters theLongChar A UTF32 character. Return Value YES if theLongChar is in the receiver, otherwise NO. Discussion This method supports the specification of 32-bit characters. Availability Available in iOS 2.0 and later. See Also – characterIsMember: (page 228) Declared in NSCharacterSet.h Constants NSOpenStepUnicodeReservedBase Specifies lower bound for a Unicode character range reserved for Apple’s corporate use. enum { NSOpenStepUnicodeReservedBase = 0xF400 }; Constants NSOpenStepUnicodeReservedBase Specifies lower bound for a Unicode character range reserved for Apple’s corporate use (the range is 0xF400–0xF8FF). Available in iOS 2.0 and later. Declared in NSCharacterSet.h. Declared in NSCharacterSet.h NSCharacterSet Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 230Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSCoder.h Foundation/NSKeyedArchiver.h Foundation/NSGeometry.h Companion guide Archives and Serializations Programming Guide Related sample code AccelerometerGraph CopyPasteTile GLImageProcessing HeadsUpUI SpeakHere Overview The NSCoder abstract class declares the interface used by concrete subclasses to transfer objects and other Objective-C data items between memory and some other format. This capability provides the basis for archiving (where objects and data items are stored on disk) and distribution (where objects and data items are copied between different processes or threads). The concrete subclasses provided by Foundation for these purposes are NSArchiver, NSUnarchiver, NSKeyedArchiver, NSKeyedUnarchiver, and NSPortCoder. Concrete subclasses of NSCoder are referred to in general as coder classes, and instances of these classes as coder objects (or simply coders). A coder object that can only encode values is referred to as an encoder object, and one that can only decode values as a decoder object. NSCoder operates on objects, scalars, C arrays, structures, and strings, and on pointers to these types. It does not handle types whose implementation varies across platforms, such as union, void *, function pointers, and long chains of pointers. A coder object stores object type information along with the data, so an object 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 231 NSCoder Class Referencedecoded from a stream of bytes is normally of the same class as the object that was originally encoded into the stream. An object can change its class when encoded, however; this is described in Archives and Serializations Programming Guide. Subclassing Notes For details of how to create a subclass of NSCoder, see “Subclassing NSCoder” in Archives and Serializations Programming Guide. Tasks Testing Coder – allowsKeyedCoding (page 235) Returns a Boolean value that indicates whether the receiver supports keyed coding of objects. – containsValueForKey: (page 236) Returns a Boolean value that indicates whether an encoded value is available for a string. Encoding Data – encodeArrayOfObjCType:count:at: (page 244) Encodes an array of count items, whose Objective-C type is given by itemType. – encodeBool:forKey: (page 244) Encodes boolv and associates it with the string key. – encodeBycopyObject: (page 245) Can be overridden by subclasses to encode object so that a copy, rather than a proxy, is created upon decoding. – encodeByrefObject: (page 245) Can be overridden by subclasses to encode object so that a proxy, rather than a copy, is created upon decoding. – encodeBytes:length: (page 246) Encodes a buffer of data whose types are unspecified. – encodeBytes:length:forKey: (page 246) Encodes a buffer of data, bytesp, whose length is specified by lenv, and associates it with the string key. NSCoder Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 232– encodeConditionalObject: (page 247) Can be overridden by subclasses to conditionally encode object, preserving common references to that object. – encodeConditionalObject:forKey: (page 247) Conditionally encodes a reference to objv and associates it with the string key only if objv has been unconditionally encoded with encodeObject:forKey: (page 252). – encodeDataObject: (page 248) Encodes a given NSData object. – encodeDouble:forKey: (page 248) Encodes realv and associates it with the string key. – encodeFloat:forKey: (page 249) Encodes realv and associates it with the string key. – encodeInt:forKey: (page 250) Encodes intv and associates it with the string key. – encodeInteger:forKey: (page 251) Encodes a given NSInteger and associates it with a given key. – encodeInt32:forKey: (page 249) Encodes the 32-bit integer intv and associates it with the string key. – encodeInt64:forKey: (page 250) Encodes the 64-bit integer intv and associates it with the string key. – encodeObject: (page 251) Encodes object. – encodeObject:forKey: (page 252) Encodes the object objv and associates it with the string key. – encodeRootObject: (page 252) Can be overridden by subclasses to encode an interconnected group of Objective-C objects, starting with rootObject. – encodeValueOfObjCType:at: (page 253) Must be overridden by subclasses to encode a single value residing at address, whose Objective-C type is given by valueType. – encodeValuesOfObjCTypes: (page 253) Encodes a series of values of potentially differing Objective-C types. NSCoder Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 233Decoding Data – decodeArrayOfObjCType:count:at: (page 236) Decodes an array of count items, whose Objective-C type is given by itemType. – decodeBoolForKey: (page 237) Decodes and returns a boolean value that was previously encoded with encodeBool:forKey: (page 244) and associated with the string key. – decodeBytesForKey:returnedLength: (page 237) Decodes a buffer of data that was previously encoded with encodeBytes:length:forKey: (page 246) and associated with the string key. – decodeBytesWithReturnedLength: (page 238) Decodes a buffer of data whose types are unspecified. – decodeDataObject (page 238) Decodes and returns an NSData object that was previously encoded with encodeDataObject: (page 248). Subclasses must override this method. – decodeDoubleForKey: (page 239) Decodes and returns a double value that was previously encoded with either encodeFloat:forKey: (page 249) or encodeDouble:forKey: (page 248) and associated with the string key. – decodeFloatForKey: (page 239) Decodes and returns a float value that was previously encoded with encodeFloat:forKey: (page 249) or encodeDouble:forKey: (page 248) and associated with the string key. – decodeIntForKey: (page 241) Decodes and returns an int value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251), encodeInt32:forKey: (page 249), or encodeInt64:forKey: (page 250) and associated with the string key. – decodeIntegerForKey: (page 240) Decodes and returns an NSInteger value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251), encodeInt32:forKey: (page 249), or encodeInt64:forKey: (page 250) and associated with the string key. – decodeInt32ForKey: (page 240) Decodes and returns a 32-bit integer value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251), encodeInt32:forKey: (page 249), or encodeInt64:forKey: (page 250) and associated with the string key. NSCoder Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 234– decodeInt64ForKey: (page 240) Decodes and returns a 64-bit integer value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251), encodeInt32:forKey: (page 249), or encodeInt64:forKey: (page 250) and associated with the string key. – decodeObject (page 241) Decodes an Objective-C object that was previously encoded with any of the encode...Object: methods. – decodeObjectForKey: (page 242) Decodes and returns an autoreleased Objective-C object that was previously encoded with encodeObject:forKey: (page 252) or encodeConditionalObject:forKey: (page 247) and associated with the string key. – decodeValueOfObjCType:at: (page 242) Decodes a single value, whose Objective-C type is given by valueType. – decodeValuesOfObjCTypes: (page 243) Decodes a series of potentially different Objective-C types. Managing Zones – objectZone (page 254) Returns the memory zone used to allocate decoded objects. – setObjectZone: (page 254) NSCoder’s implementation of this method does nothing. Getting Version Information – systemVersion (page 255) During encoding, this method should return the system version currently in effect. – versionForClassName: (page 255) Returns the version in effect for the class with a given name. Instance Methods allowsKeyedCoding Returns a Boolean value that indicates whether the receiver supports keyed coding of objects. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 235- (BOOL)allowsKeyedCoding Discussion The default implementation returns NO. Concrete subclasses that support keyed coding, such as NSKeyedArchiver, need to override this method to return YES. Availability Available in iOS 2.0 and later. Declared in NSCoder.h containsValueForKey: Returns a Boolean value that indicates whether an encoded value is available for a string. - (BOOL)containsValueForKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. The string is passed as key. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeArrayOfObjCType:count:at: Decodes an array of count items, whose Objective-C type is given by itemType. - (void)decodeArrayOfObjCType:(const char *)itemType count:(NSUInteger)count at:(void *)address Discussion The items are decoded into the buffer beginning at address, which must be large enough to contain them all. itemType must contain exactly one type code. NSCoder’s implementation invokes decodeValueOfObjCType:at: (page 242) to decode the entire array of items. If you use this method to decode an array of Objective-C objects, you are responsible for releasing each object. This method matches an encodeArrayOfObjCType:count:at: (page 244) message used during encoding. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 236For information on creating an Objective-C type code suitable for itemType, see “Type Encodings”. Availability Available in iOS 2.0 and later. See Also – decodeValuesOfObjCTypes: (page 243) Declared in NSCoder.h decodeBoolForKey: Decodes and returns a boolean value that was previously encoded with encodeBool:forKey: (page 244) and associated with the string key. - (BOOL)decodeBoolForKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeBytesForKey:returnedLength: Decodes a buffer of data that was previously encoded with encodeBytes:length:forKey: (page 246) and associated with the string key. - (const uint8_t *)decodeBytesForKey:(NSString *)key returnedLength:(NSUInteger *)lengthp Discussion The buffer’s length is returned by reference in lengthp. The returned bytes are immutable. Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 237See Also – encodeBytes:length:forKey: (page 246) Declared in NSCoder.h decodeBytesWithReturnedLength: Decodes a buffer of data whose types are unspecified. - (void *)decodeBytesWithReturnedLength:(NSUInteger *)numBytes Discussion NSCoder’s implementation invokes decodeValueOfObjCType:at: (page 242) to decode the data as a series of bytes, which this method then places into a buffer and returns. The buffer’s length is returned by reference in numBytes. If you need the bytes beyond the scope of the current autorelease pool, you must copy them. This method matches an encodeBytes:length: (page 246) message used during encoding. Availability Available in iOS 2.0 and later. See Also – encodeArrayOfObjCType:count:at: (page 244) Declared in NSCoder.h decodeDataObject DecodesandreturnsanNSDataobjectthatwaspreviouslyencodedwithencodeDataObject: (page 248).Subclasses must override this method. - (NSData *)decodeDataObject Discussion The implementation of your overriding method must match the implementation of your encodeDataObject: (page 248) method. For example, a typical encodeDataObject: (page 248) method encodes the number of bytes of data followed by the bytes themselves. Your override of this method must read the number of bytes, create an NSData object of the appropriate size, and decode the bytes into the new NSData object. Your overriding method should return an autoreleased NSData object. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 238Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeDoubleForKey: Decodes and returns a double value that was previously encoded with either encodeFloat:forKey: (page 249) or encodeDouble:forKey: (page 248) and associated with the string key. - (double)decodeDoubleForKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeFloatForKey: Decodes and returns a float value that was previously encoded with encodeFloat:forKey: (page 249) or encodeDouble:forKey: (page 248) and associated with the string key. - (float)decodeFloatForKey:(NSString *)key Discussion If the value was encoded as a double, the extra precision is lost. Also, if the encoded real value does not fit into a float, the method raises an NSRangeException. Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Related Sample Code CopyPasteTile Declared in NSCoder.h NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 239decodeInt32ForKey: Decodes and returns a 32-bit integer value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251),encodeInt32:forKey: (page 249),orencodeInt64:forKey: (page 250)and associated with the string key. - (int32_t)decodeInt32ForKey:(NSString *)key Discussion If the encoded integer does not fit into a 32-bit integer, the method raises an NSRangeException. Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeInt64ForKey: Decodes and returns a 64-bit integer value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251),encodeInt32:forKey: (page 249),orencodeInt64:forKey: (page 250)and associated with the string key. - (int64_t)decodeInt64ForKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeIntegerForKey: Decodes and returns an NSInteger value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251),encodeInt32:forKey: (page 249),orencodeInt64:forKey: (page 250)and associated with the string key. - (NSInteger)decodeIntegerForKey:(NSString *)key NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 240Discussion If the encoded integer does not fit into the NSInteger size, the method raises an NSRangeException. Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeIntForKey: Decodes and returns an int value that was previously encoded with encodeInt:forKey: (page 250), encodeInteger:forKey: (page 251),encodeInt32:forKey: (page 249),orencodeInt64:forKey: (page 250)and associated with the string key. - (int)decodeIntForKey:(NSString *)key Discussion If the encoded integer does not fit into the default integer size, the method raises an NSRangeException. Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Declared in NSCoder.h decodeObject Decodes an Objective-C object that was previously encoded with any of the encode...Object: methods. - (id)decodeObject Discussion NSCoder’s implementation invokes decodeValueOfObjCType:at: (page 242) to decode the object data. Subclasses may need to override this method if they override any of the corresponding encode...Object: methods. For example, if an object was encoded conditionally using the encodeConditionalObject: (page 247) method, this method needs to check whether the object had actually been encoded. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 241The implementation for the concrete subclass NSUnarchiver returns an object that is retained by the unarchiver and is released when the unarchiver is deallocated. Therefore, you must retain the returned object before releasing the unarchiver. NSKeyedUnarchiver’s implementation, however, returns an autoreleased object, so its life is the same as the current autorelease pool instead of the keyed unarchiver. Availability Available in iOS 2.0 and later. See Also – encodeBycopyObject: (page 245) – encodeByrefObject: (page 245) – encodeObject: (page 251) Declared in NSCoder.h decodeObjectForKey: Decodes and returns an autoreleased Objective-C object that was previously encoded with encodeObject:forKey: (page 252) or encodeConditionalObject:forKey: (page 247) and associated with the string key. - (id)decodeObjectForKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. Related Sample Code CopyPasteTile Declared in NSCoder.h decodeValueOfObjCType:at: Decodes a single value, whose Objective-C type is given by valueType. - (void)decodeValueOfObjCType:(const char *)valueType at:(void *)data NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 242Discussion valueType must contain exactly one type code, and the buffer specified by data must be large enough to hold the value corresponding to that type code. For information on creating an Objective-C type code suitable for valueType, see “Type Encodings”. Subclasses must override this method and provide an implementation to decode the value. In your overriding implementation, decode the value into the buffer beginning at data. If your overriding method is capable of decoding an Objective-C object, your method must also retain that object. Clients of this method are then responsible for releasing the object. This method matches an encodeValueOfObjCType:at: (page 253) message used during encoding. Availability Available in iOS 2.0 and later. See Also – decodeArrayOfObjCType:count:at: (page 236) – decodeValuesOfObjCTypes: (page 243) – decodeObject (page 241) Declared in NSCoder.h decodeValuesOfObjCTypes: Decodes a series of potentially different Objective-C types. - (void)decodeValuesOfObjCTypes:(const char *)valueTypes, ... Discussion valueTypes is a single string containing any number of type codes. The variable arguments to this method consist of one or more pointer arguments, each of which specifies the buffer in which to place a single decoded value. For each type code in valueTypes, you must specify a corresponding pointer argument whose buffer is large enough to hold the decoded value. If you use this method to decode Objective-C objects, you are responsible for releasing them. This method matches an encodeValuesOfObjCTypes: (page 253) message used during encoding. NSCoder’s implementation invokes decodeValueOfObjCType:at: (page 242) to decode individual types. Subclasses that implement the decodeValueOfObjCType:at: (page 242) method do not need to override this method. For information on creating Objective-C type codes suitable for valueTypes, see “Type Encodings”. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 243Availability Available in iOS 2.0 and later. See Also – decodeArrayOfObjCType:count:at: (page 236) Declared in NSCoder.h encodeArrayOfObjCType:count:at: Encodes an array of count items, whose Objective-C type is given by itemType. - (void)encodeArrayOfObjCType:(const char *)itemType count:(NSUInteger)count at:(const void *)address Discussion The values are encoded from the buffer beginning at address. itemType must contain exactly one type code. NSCoder’s implementation invokes encodeValueOfObjCType:at: (page 253) to encode the entire array of items. Subclasses that implement the encodeValueOfObjCType:at: (page 253) method do not need to override this method. This method must be matched by a subsequent decodeArrayOfObjCType:count:at: (page 236) message. For information on creating an Objective-C type code suitable for itemType, see “Type Encodings”. Availability Available in iOS 2.0 and later. See Also – encodeValueOfObjCType:at: (page 253) – encodeValuesOfObjCTypes: (page 253) – encodeBytes:length: (page 246) Declared in NSCoder.h encodeBool:forKey: Encodes boolv and associates it with the string key. - (void)encodeBool:(BOOL)boolv forKey:(NSString *)key NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 244Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeBoolForKey: (page 237) Declared in NSCoder.h encodeBycopyObject: Can be overridden by subclasses to encode object so that a copy, rather than a proxy, is created upon decoding. - (void)encodeBycopyObject:(id)object Discussion NSCoder’s implementation simply invokes encodeObject: (page 251). This method must be matched by a corresponding decodeObject (page 241) message. Availability Available in iOS 2.0 and later. See Also – encodeRootObject: (page 252) – encodeConditionalObject: (page 247) – encodeByrefObject: (page 245) Declared in NSCoder.h encodeByrefObject: Can be overridden by subclasses to encode object so that a proxy, rather than a copy, is created upon decoding. - (void)encodeByrefObject:(id)object Discussion NSCoder’s implementation simply invokes encodeObject: (page 251). NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 245This method must be matched by a corresponding decodeObject (page 241) message. Availability Available in iOS 2.0 and later. See Also – encodeBycopyObject: (page 245) Declared in NSCoder.h encodeBytes:length: Encodes a buffer of data whose types are unspecified. - (void)encodeBytes:(const void *)address length:(NSUInteger)numBytes Discussion The buffer to be encoded begins at address, and its length in bytes is given by numBytes. This method must be matched by a corresponding decodeBytesWithReturnedLength: (page 238) message. Availability Available in iOS 2.0 and later. See Also – encodeArrayOfObjCType:count:at: (page 244) Declared in NSCoder.h encodeBytes:length:forKey: Encodes a buffer of data, bytesp, whose length is specified by lenv, and associates it with the string key. - (void)encodeBytes:(const uint8_t *)bytesp length:(NSUInteger)lenv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 246See Also – decodeBytesForKey:returnedLength: (page 237) Declared in NSCoder.h encodeConditionalObject: Can be overridden by subclasses to conditionally encode object, preserving common references to that object. - (void)encodeConditionalObject:(id)object Discussion In the overriding method, object should be encoded only if it’s unconditionally encoded elsewhere (with any other encode...Object: method). This method must be matched by a subsequent decodeObject (page 241) message. Upon decoding, if object was never encoded unconditionally, decodeObject returns nil in place of object. However, if object was encoded unconditionally, all references to object must be resolved. NSCoder’s implementation simply invokes encodeObject: (page 251). Availability Available in iOS 2.0 and later. See Also – encodeRootObject: (page 252) – encodeObject: (page 251) – encodeBycopyObject: (page 245) Declared in NSCoder.h encodeConditionalObject:forKey: Conditionally encodes a reference to objv and associates it with the string key only if objv has been unconditionally encoded with encodeObject:forKey: (page 252). - (void)encodeConditionalObject:(id)objv forKey:(NSString *)key Discussion Subclasses must override this method if they support keyed coding. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 247The encoded object is decoded with the decodeObjectForKey: (page 242) method. If objv was never encoded unconditionally, decodeObjectForKey: (page 242) returns nil in place of objv. Availability Available in iOS 2.0 and later. Declared in NSCoder.h encodeDataObject: Encodes a given NSData object. - (void)encodeDataObject:(NSData *)data Discussion Subclasses must override this method. This method must be matched by a subsequent decodeDataObject (page 238) message. Availability Available in iOS 2.0 and later. See Also – encodeObject: (page 251) Declared in NSCoder.h encodeDouble:forKey: Encodes realv and associates it with the string key. - (void)encodeDouble:(double)realv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeDoubleForKey: (page 239) NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 248– decodeFloatForKey: (page 239) Declared in NSCoder.h encodeFloat:forKey: Encodes realv and associates it with the string key. - (void)encodeFloat:(float)realv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeFloatForKey: (page 239) – decodeDoubleForKey: (page 239) Related Sample Code CopyPasteTile Declared in NSCoder.h encodeInt32:forKey: Encodes the 32-bit integer intv and associates it with the string key. - (void)encodeInt32:(int32_t)intv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeIntForKey: (page 241) – decodeIntegerForKey: (page 240) – decodeInt32ForKey: (page 240) – decodeInt64ForKey: (page 240) NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 249Declared in NSCoder.h encodeInt64:forKey: Encodes the 64-bit integer intv and associates it with the string key. - (void)encodeInt64:(int64_t)intv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeIntForKey: (page 241) – decodeIntegerForKey: (page 240) – decodeInt32ForKey: (page 240) – decodeInt64ForKey: (page 240) Declared in NSCoder.h encodeInt:forKey: Encodes intv and associates it with the string key. - (void)encodeInt:(int)intv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeIntForKey: (page 241) – decodeIntegerForKey: (page 240) – decodeInt32ForKey: (page 240) – decodeInt64ForKey: (page 240) NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 250Declared in NSCoder.h encodeInteger:forKey: Encodes a given NSInteger and associates it with a given key. - (void)encodeInteger:(NSInteger)intv forKey:(NSString *)key Discussion Subclasses must override this method if they perform keyed coding. Availability Available in iOS 2.0 and later. See Also – decodeIntForKey: (page 241) – decodeIntegerForKey: (page 240) – decodeInt32ForKey: (page 240) – decodeInt64ForKey: (page 240) Declared in NSCoder.h encodeObject: Encodes object. - (void)encodeObject:(id)object Discussion NSCoder’s implementation simply invokes encodeValueOfObjCType:at: (page 253) to encode object. Subclasses can override this method to encode a reference to object instead of object itself. For example, NSArchiver detects duplicate objects and encodes a reference to the original object rather than encode the same object twice. This method must be matched by a subsequent decodeObject (page 241) message. Availability Available in iOS 2.0 and later. See Also – encodeRootObject: (page 252) NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 251– encodeConditionalObject: (page 247) – encodeBycopyObject: (page 245) Declared in NSCoder.h encodeObject:forKey: Encodes the object objv and associates it with the string key. - (void)encodeObject:(id)objv forKey:(NSString *)key Discussion Subclasses must override this method to identify multiple encodings of objv and encode a reference to objv instead. For example, NSKeyedArchiver detects duplicate objects and encodes a reference to the original object rather than encode the same object twice. Availability Available in iOS 2.0 and later. See Also – decodeObjectForKey: (page 242) Related Sample Code CopyPasteTile Declared in NSCoder.h encodeRootObject: Can be overridden by subclasses to encode an interconnected group of Objective-C objects, starting with rootObject. - (void)encodeRootObject:(id)rootObject Discussion NSCoder’s implementation simply invokes encodeObject: (page 251). This method must be matched by a subsequent decodeObject (page 241) message. Availability Available in iOS 2.0 and later. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 252See Also – encodeObject: (page 251) – encodeConditionalObject: (page 247) – encodeBycopyObject: (page 245) Declared in NSCoder.h encodeValueOfObjCType:at: Must be overridden by subclasses to encode a single value residing at address, whose Objective-C type is given by valueType. - (void)encodeValueOfObjCType:(const char *)valueType at:(const void *)address Discussion valueType must contain exactly one type code. This method must be matched by a subsequent decodeValueOfObjCType:at: (page 242) message. For information on creating an Objective-C type code suitable for valueType, see “Type Encodings”. Availability Available in iOS 2.0 and later. See Also – encodeArrayOfObjCType:count:at: (page 244) – encodeValuesOfObjCTypes: (page 253) Declared in NSCoder.h encodeValuesOfObjCTypes: Encodes a series of values of potentially differing Objective-C types. - (void)encodeValuesOfObjCTypes:(const char *)valueTypes, ... Discussion valueTypes is a single string containing any number of type codes. The variable arguments to this method consist of one or more pointer arguments, each of which specifies a buffer containing the value to be encoded. For each type code in valueTypes, you must specify a corresponding pointer argument. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 253This method must be matched by a subsequent decodeValuesOfObjCTypes: (page 243) message. NSCoder’s implementation invokes encodeValueOfObjCType:at: (page 253) to encode individual types. Subclasses that implement the encodeValueOfObjCType:at: (page 253) method do not need to override this method. However, subclasses that provide a more efficient approach for encoding a series of values may override this method to implement that approach. For information on creating Objective-C type codes suitable for valueTypes, see “Type Encodings”. Availability Available in iOS 2.0 and later. See Also – encodeArrayOfObjCType:count:at: (page 244) – encodeValueOfObjCType:at: (page 253) Declared in NSCoder.h objectZone Returns the memory zone used to allocate decoded objects. - (NSZone *)objectZone Discussion NSCoder’s implementation simply returns the default memory zone, as given by NSDefaultMallocZone(). Subclasses must override this method and the setObjectZone: (page 254) method to allow objects to be decoded into a zone other than the default zone. In its overriding implementation of this method, your subclass should return the current memory zone (if one has been set) or the default zone (if no other zone has been set). Availability Available in iOS 2.0 and later. Declared in NSCoder.h setObjectZone: NSCoder’s implementation of this method does nothing. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 254- (void)setObjectZone:(NSZone *)zone Discussion Can be overridden by subclasses to set the memory zone used to allocate decoded objects. Subclasses must override this method and objectZone (page 254) to allow objects to be decoded into a zone other than the default zone. In its overriding implementation of this method, your subclass should store a reference to the current memory zone. Availability Available in iOS 2.0 and later. Declared in NSCoder.h systemVersion During encoding, this method should return the system version currently in effect. - (unsigned)systemVersion Discussion During decoding, this method should return the version that was in effect when the data was encoded. By default, this method returns the current system version, which is appropriate for encoding but not for decoding. Subclasses that implement decoding must override this method to return the system version of the data being decoded. Availability Available in iOS 2.0 and later. Declared in NSCoder.h versionForClassName: Returns the version in effect for the class with a given name. - (NSInteger)versionForClassName:(NSString *)className Return Value The version in effect for the class named className or NSNotFound if no class named className exists. NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 255Discussion When encoding, this method returns the current version number of the class. When decoding, this method returns the version number of the class being decoded. Subclasses must override this method. Special Considerations The version number applies to NSArchiver/NSUnarchiver, but not to NSKeyedArchiver/NSKeyedUnarchiver. A keyed archiver does not encode class version numbers. Availability Available in iOS 2.0 and later. See Also setVersion: (page 1217) (NSObject) version (page 1219) (NSObject) Declared in NSCoder.h NSCoder Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 256Inherits from NSPredicate : NSObject Conforms to NSCoding (NSPredicate) NSCopying (NSPredicate) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 3.0 and later. Declared in Foundation/NSComparisonPredicate.h Companion guide Predicate Programming Guide Overview NSComparisonPredicate is a subclass of NSPredicate that you use to compare expressions. You use comparison predicates to compare the results of two expressions. You create a comparison predicate with an operator, a left expression, and a right expression. You represent the expressions using instances of the NSExpression class. When you evaluate the predicate, it returns as a BOOL value the result of invoking the operator with the results of evaluating the expressions. Tasks Creating Comparison Predicates + predicateWithLeftExpression:rightExpression:customSelector: (page 258) Returns a new predicate formed by combining the left and right expressions using a given selector. + predicateWithLeftExpression:rightExpression:modifier:type:options: (page 259) Creates and returns a predicate of a given type formed by combining given left and right expressions using a given modifier and options. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 257 NSComparisonPredicate Class Reference– initWithLeftExpression:rightExpression:customSelector: (page 261) Initializes a predicate formed by combining given left and right expressions using a given selector. – initWithLeftExpression:rightExpression:modifier:type:options: (page 261) Initializes a predicate to a given type formed by combining given left and right expressions using a given modifier and options. Getting Information About a Comparison Predicate – comparisonPredicateModifier (page 260) Returns the comparison predicate modifier for the receiver. – customSelector (page 260) Returns the selector for the receiver. – leftExpression (page 262) Returns the left expression for the receiver. – options (page 262) Returns the options that are set for the receiver. – predicateOperatorType (page 263) Returns the predicate type for the receiver. – rightExpression (page 263) Returns the right expression for the receiver. Class Methods predicateWithLeftExpression:rightExpression:customSelector: Returns a new predicate formed by combining the left and right expressions using a given selector. + (NSPredicate *)predicateWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs customSelector:(SEL)selector Parameters lhs The left hand side expression. rhs The right hand side expression. NSComparisonPredicate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 258selector The selector to use for comparison. The method defined by the selector must take a single argument and return a BOOL value. Return Value A new predicate formed by combining the left and right expressions using selector. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h predicateWithLeftExpression:rightExpression:modifier:type:options: Creates and returns a predicate of a given type formed by combining given left and right expressions using a given modifier and options. + (NSPredicate *)predicateWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs modifier:(NSComparisonPredicateModifier)modifier type:(NSPredicateOperatorType)type options:(NSUInteger)options Parameters lhs The left hand expression. rhs The right hand expression. modifier The modifier to apply. type The predicate operator type. options The options to apply (see “NSComparisonPredicate Options” (page 264)). For no options, pass 0. Return Value A new predicate of type type formed by combining the given left and right expressions using the modifier and options. Availability Available in iOS 3.0 and later. NSComparisonPredicate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 259Declared in NSComparisonPredicate.h Instance Methods comparisonPredicateModifier Returns the comparison predicate modifier for the receiver. - (NSComparisonPredicateModifier)comparisonPredicateModifier Return Value The comparison predicate modifier for the receiver. Discussion The default value is NSDirectPredicateModifier (page 264). Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h customSelector Returns the selector for the receiver. - (SEL)customSelector Return Value The selector for the receiver, or NULL if there is none. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h NSComparisonPredicate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 260initWithLeftExpression:rightExpression:customSelector: Initializes a predicate formed by combining given left and right expressions using a given selector. - (id)initWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs customSelector:(SEL)selector Parameters lhs The left hand expression. rhs The right hand expression. selector The selector to use. The method defined by the selector must take a single argument and return a BOOL value. Return Value The receiver, initialized by combining the left and right expressions using selector. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h initWithLeftExpression:rightExpression:modifier:type:options: Initializes a predicate to a given type formed by combining given left and right expressions using a given modifier and options. - (id)initWithLeftExpression:(NSExpression *)lhs rightExpression:(NSExpression *)rhs modifier:(NSComparisonPredicateModifier)modifier type:(NSPredicateOperatorType)type options:(NSUInteger)options Parameters lhs The left hand expression. rhs The right hand expression. modifier The modifier to apply. NSComparisonPredicate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 261type The predicate operator type. options The options to apply (see “NSComparisonPredicate Options” (page 264)). For no options, pass 0. Return Value The receiver, initialized to a predicate of type type formed by combining the left and right expressions using the modifier and options. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h leftExpression Returns the left expression for the receiver. - (NSExpression *)leftExpression Return Value The left expression for the receiver, or nil if there is none. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h options Returns the options that are set for the receiver. - (NSUInteger)options Return Value The options that are set for the receiver. Availability Available in iOS 3.0 and later. NSComparisonPredicate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 262Declared in NSComparisonPredicate.h predicateOperatorType Returns the predicate type for the receiver. - (NSPredicateOperatorType)predicateOperatorType Return Value The predicate type for the receiver. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h rightExpression Returns the right expression for the receiver. - (NSExpression *)rightExpression Return Value The right expression for the receiver, or nil if there is none. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h Constants NSComparisonPredicateModifier These constants describe the possible types of modifier for NSComparisonPredicate. NSComparisonPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 263enum { NSDirectPredicateModifier = 0, NSAllPredicateModifier, NSAnyPredicateModifier, }; typedef NSUInteger NSComparisonPredicateModifier; Constants NSDirectPredicateModifier A predicate to compare directly the left and right hand sides. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSAllPredicateModifier A predicate to compare all entries in the destination of a to-many relationship. The left hand side must be a collection. The corresponding predicate compares each value in the left hand side with the right hand side, and returns NO when it finds the first mismatch—or YES if all match. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSAnyPredicateModifier A predicate to match with any entry in the destination of a to-many relationship. The left hand side must be a collection. The corresponding predicate compares each value in the left hand side against the right hand side and returns YES when it finds the first match—or NO if no match is found Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h NSComparisonPredicate Options These constants describe the possible types of string comparison for NSComparisonPredicate. These options are supported for LIKE as well as all of the equality/comparison operators. NSComparisonPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 264enum { NSCaseInsensitivePredicateOption = 0x01, NSDiacriticInsensitivePredicateOption = 0x02, NSNormalizedPredicateOption = 0x04, NSLocaleSensitivePredicateOption = 0x08 }; typedef NSUInteger NSComparisonPredicateOptions; Constants NSCaseInsensitivePredicateOption A case-insensitive predicate. You represent this option in a predicate format string using a [c] following a string operation (for example, "NeXT" like[c] "next"). Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSDiacriticInsensitivePredicateOption A diacritic-insensitive predicate. You represent this option in a predicate format string using a [d] following a string operation (for example, "naïve" like[d] "naive"). Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSNormalizedPredicateOption Indicates that the strings to be compared have been preprocessed. This option supersedes NSCaseInsensitivePredicateOption and NSDiacriticInsensitivePredicateOption, and is intended as a performance optimization option. You represent this option in a predicate format string using a [n] following a string operation (for example, "WXYZlan" matches[n] ".lan"). Available in iOS 5.0 and later. Declared in NSComparisonPredicate.h. NSLocaleSensitivePredicateOption Indicates that strings to be compared using <, <=, =, =>, > should be handled in a locale-aware fashion. You represent this option in a predicate format string using a [l] following one of the <, <=, =, =>, > operators (for example, "straße" >[l] "strasse"). Availability Available in iOS 5.0 and later. Declared in NSComparisonPredicate.h NSComparisonPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 265NSPredicateOperatorType Defines the type of comparison for NSComparisonPredicate. enum { NSLessThanPredicateOperatorType = 0, NSLessThanOrEqualToPredicateOperatorType, NSGreaterThanPredicateOperatorType, NSGreaterThanOrEqualToPredicateOperatorType, NSEqualToPredicateOperatorType, NSNotEqualToPredicateOperatorType, NSMatchesPredicateOperatorType, NSLikePredicateOperatorType, NSBeginsWithPredicateOperatorType, NSEndsWithPredicateOperatorType, NSInPredicateOperatorType, NSCustomSelectorPredicateOperatorType, NSContainsPredicateOperatorType, NSBetweenPredicateOperatorType }; typedef NSUInteger NSPredicateOperatorType; Constants NSLessThanPredicateOperatorType A less-than predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSLessThanOrEqualToPredicateOperatorType A less-than-or-equal-to predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSGreaterThanPredicateOperatorType A greater-than predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSGreaterThanOrEqualToPredicateOperatorType A greater-than-or-equal-to predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSComparisonPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 266NSEqualToPredicateOperatorType An equal-to predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSNotEqualToPredicateOperatorType A not-equal-to predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSMatchesPredicateOperatorType A full regular expression matching predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSLikePredicateOperatorType A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSBeginsWithPredicateOperatorType A begins-with predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSEndsWithPredicateOperatorType An ends-with predicate. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSInPredicateOperatorType A predicate to determine if the left hand side is in the right hand side. For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side . Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSCustomSelectorPredicateOperatorType A predicate that uses a custom selector that takes a single argument and returns a BOOL value. The selector is invoked on the left hand side with the right hand side as the argument. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSComparisonPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 267NSContainsPredicateOperatorType A predicate to determine if the left hand side contains the right hand side. Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. NSBetweenPredicateOperatorType A predicate to determine if the right hand side lies at or between bounds specified by the left hand side. Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent. Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h. Availability Available in iOS 3.0 and later. Declared in NSComparisonPredicate.h NSComparisonPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 268Inherits from NSPredicate : NSObject Conforms to NSCoding (NSPredicate) NSCopying (NSPredicate) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 3.0 and later. Declared in Foundation/NSCompoundPredicate.h Companion guide Predicate Programming Guide Overview NSCompoundPredicate is a subclass of NSPredicate used to represent logical “gate” operations (AND/OR/NOT) and comparison operations. Comparison operations are based on two expressions, as represented by instances of the NSExpression class. Expressions are created for constant values, key paths, and so on. In Mac OS X v10.5 and later and in iOS, you can use NSCompoundPredicate to create an AND or OR compound predicate (but not a NOT compound predicate) using an array with 0, 1, or more elements: ● An AND predicate with no subpredicates evaluates to TRUE. ● An OR predicate with no subpredicates evaluates to FALSE. ● A compound predicate with one or more subpredicates evaluates to the truth of its subpredicates. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 269 NSCompoundPredicate Class ReferenceTasks Constructors + andPredicateWithSubpredicates: (page 270) Returns a new predicate formed by AND-ing the predicates in a given array. + notPredicateWithSubpredicate: (page 271) Returns a new predicate formed by NOT-ing a given predicate. + orPredicateWithSubpredicates: (page 271) Returns a new predicate formed by OR-ing the predicates in a given array. – initWithType:subpredicates: (page 272) Returns the receiver initialized to a given type using predicates from a given array. Getting Information About a Compound Predicate – compoundPredicateType (page 272) Returns the predicate type for the receiver. – subpredicates (page 273) Returns the array of the receiver’s subpredicates. Class Methods andPredicateWithSubpredicates: Returns a new predicate formed by AND-ing the predicates in a given array. + (NSPredicate *)andPredicateWithSubpredicates:(NSArray *)subpredicates Parameters subpredicates An array of NSPredicate objects. Return Value A new predicate formed by AND-ing the predicates specified by subpredicates. Discussion An AND predicate with no subpredicates evaluates to TRUE. NSCompoundPredicate Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 270Special Considerations For applications linked on Mac OS X v10.5 or later, the subpredicates array is copied. For applications linked on Mac OS X v10.4, the subpredicates array is retained (for binary compatibility). Availability Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h notPredicateWithSubpredicate: Returns a new predicate formed by NOT-ing a given predicate. + (NSPredicate *)notPredicateWithSubpredicate:(NSPredicate *)predicate Parameters predicate A predicate. Return Value A new predicate formed by NOT-ing the predicate specified by predicate. Special Considerations For applications linked on Mac OS X v10.5 or later, the subpredicates array is copied. For applications linked on Mac OS X v10.4, the subpredicates array is retained (for binary compatibility). Availability Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h orPredicateWithSubpredicates: Returns a new predicate formed by OR-ing the predicates in a given array. + (NSPredicate *)orPredicateWithSubpredicates:(NSArray *)subpredicates Parameters subpredicates An array of NSPredicate objects. NSCompoundPredicate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 271Return Value A new predicate formed by OR-ing the predicates specified by subpredicates. Discussion An OR predicate with no subpredicates evaluates to FALSE. Special Considerations For applications linked on Mac OS X v10.5 or later, the subpredicates array is copied. For applications linked on Mac OS X v10.4, the subpredicates array is retained (for binary compatibility). Availability Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h Instance Methods compoundPredicateType Returns the predicate type for the receiver. - (NSCompoundPredicateType)compoundPredicateType Return Value The predicate type for the receiver. Availability Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h initWithType:subpredicates: Returns the receiver initialized to a given type using predicates from a given array. - (id)initWithType:(NSCompoundPredicateType)type subpredicates:(NSArray *)subpredicates NSCompoundPredicate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 272Parameters type The type of the new predicate. subpredicates An array of NSPredicate objects. Return Value The receiver initialized with its type set to type and subpredicates array to subpredicates. Special Considerations For applications linked on Mac OS X v10.5 or later, the subpredicates array is copied. For applications linked on Mac OS X v10.4, the subpredicates array is retained (for binary compatibility). Availability Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h subpredicates Returns the array of the receiver’s subpredicates. - (NSArray *)subpredicates Return Value The array of the receiver’s subpredicates. Availability Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h Constants Compound Predicate Types These constants describe the possible types of NSCompoundPredicate. NSCompoundPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 273typedef enum { NSNotPredicateType = 0, NSAndPredicateType, NSOrPredicateType, } NSCompoundPredicateType; Constants NSNotPredicateType A logical NOT predicate. Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h. NSAndPredicateType A logical AND predicate. Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h. NSOrPredicateType A logical OR predicate. Available in iOS 3.0 and later. Declared in NSCompoundPredicate.h. Declared in NSCompoundPredicate.h NSCompoundPredicate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 274Inherits from NSObject Conforms to NSLocking NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSLock.h Companion guide Threading Programming Guide Overview The NSCondition class implements a condition variable whose semantics follow those used for POSIX-style conditions. A condition object acts as both a lock and a checkpoint in a given thread. The lock protects your code while it tests the condition and performs the task triggered by the condition. The checkpoint behavior requires that the condition be true before the thread proceeds with its task. While the condition is not true, the thread blocks. It remains blocked until another thread signals the condition object. The semantics for using an NSCondition object are as follows: 1. Lock the condition object. 2. Test a boolean predicate. (This predicate is a boolean flag or other variable in your code that indicates whether it is safe to perform the task protected by the condition.) 3. If the boolean predicate is false, call the condition object’s wait or waitUntilDate: method to block the thread. Upon returning from these methods, go to step 2 to retest your boolean predicate. (Continue waiting and retesting the predicate until it is true.) 4. If the boolean predicate is true, perform the task. 5. Optionally update any predicates (or signal any conditions) affected by your task. 6. When your task is done, unlock the condition object. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 275 NSCondition Class ReferenceThe pseudocode for performing the preceding steps would therefore look something like the following: lock the condition while (!(boolean_predicate)) { wait on condition } do protected work (optionally, signal or broadcast the condition again or change a predicate value) unlock the condition Whenever you use a condition object, the first step is to lock the condition. Locking the condition ensures that your predicate and task code are protected from interference by other threads using the same condition. Once you have completed your task, you can set other predicates or signal other conditions based on the needs of your code. You should always set predicates and signal conditions while holding the condition object’s lock. When a thread waits on a condition, the condition object unlocks its lock and blocks the thread. When the condition is signaled, the system wakes up the thread. The condition object then reacquires its lock before returning from the wait or waitUntilDate: method. Thus, from the point of view of the thread, it is as if it always held the lock. A boolean predicate is an important part of the semantics of using conditions because of the way signaling works. Signaling a condition does not guarantee that the condition itself is true. There are timing issues involved in signaling that may cause false signals to appear. Using a predicate ensures that these spurious signals do not cause you to perform work before it is safe to do so. The predicate itself is simply a flag or other variable in your code that you test in order to acquire a Boolean result. For more information on how to use conditions, see Using POSIX Thread Locks in Threading Programming Guide. Tasks Waiting for the Lock – wait (page 279) Blocks the current thread until the condition is signaled. – waitUntilDate: (page 279) Blocks the current thread until the condition is signaled or the specified time limit is reached. NSCondition Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 276Signaling Waiting Threads – signal (page 278) Signals the condition, waking up one thread waiting on it. – broadcast (page 277) Signals the condition, waking up all threads waiting on it. Accessor Methods – setName: (page 278) Assigns a name to the receiver. – name (page 277) Returns the name associated with the receiver. Instance Methods broadcast Signals the condition, waking up all threads waiting on it. - (void)broadcast Discussion If no threads are waiting on the condition, this method does nothing. To avoid race conditions, you should invoke this method only while the receiver is locked. Availability Available in iOS 2.0 and later. Declared in NSLock.h name Returns the name associated with the receiver. - (NSString *)name NSCondition Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 277Return Value The name of the receiver. Availability Available in iOS 2.0 and later. See Also – setName: (page 278) Declared in NSLock.h setName: Assigns a name to the receiver. - (void)setName:(NSString *)newName Parameters newName The new name for the receiver. This method makes a copy of the specified string. Discussion You can use a name string to identify a condition object within your code. Cocoa also uses this name as part of any error descriptions involving the receiver. Availability Available in iOS 2.0 and later. See Also – name (page 277) Declared in NSLock.h signal Signals the condition, waking up one thread waiting on it. - (void)signal NSCondition Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 278Discussion You use this method to wake up one thread that is waiting on the condition. You may call this method multiple times to wake up multiple threads. If no threads are waiting on the condition, this method does nothing. To avoid race conditions, you should invoke this method only while the receiver is locked. Availability Available in iOS 2.0 and later. Declared in NSLock.h wait Blocks the current thread until the condition is signaled. - (void)wait Discussion You must lock the receiver prior to calling this method. Availability Available in iOS 2.0 and later. See Also – lock (page 2096) (NSLocking) Declared in NSLock.h waitUntilDate: Blocks the current thread until the condition is signaled or the specified time limit is reached. - (BOOL)waitUntilDate:(NSDate *)limit Parameters limit The time at which to wake up the thread if the condition has not been signaled. Return Value YES if the condition was signaled; otherwise, NO if the time limit was reached. NSCondition Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 279Discussion You must lock the receiver prior to calling this method. Availability Available in iOS 2.0 and later. See Also – lock (page 2096) (NSLocking) Declared in NSLock.h NSCondition Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 280Inherits from NSObject Conforms to NSLocking NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSLock.h Companion guide Threading Programming Guide Overview The NSConditionLock class defines objects whose locks can be associated with specific, user-defined conditions. Using an NSConditionLock object, you can ensure that a thread can acquire a lock only if a certain condition is met. Once it has acquired the lock and executed the critical section of code, the thread can relinquish the lock and set the associated condition to something new. The conditions themselves are arbitrary: you define them as needed for your application. Adopted Protocols NSLocking lock (page 2096) unlock (page 2096) 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 281 NSConditionLock Class ReferenceTasks Initializing an NSConditionLock Object – initWithCondition: (page 283) Initializes a newly allocated NSConditionLock object and sets its condition. Returning the Condition – condition (page 283) Returns the condition associated with the receiver. Acquiring and Releasing a Lock – lockBeforeDate: (page 283) Attempts to acquire a lock before a specified moment in time. – lockWhenCondition: (page 284) Attempts to acquire a lock. – lockWhenCondition:beforeDate: (page 285) Attempts to acquire a lock before a specified moment in time. – tryLock (page 286) Attempts to acquire a lock without regard to the receiver’s condition. – tryLockWhenCondition: (page 287) Attempts to acquire a lock if the receiver’s condition is equal to the specified condition. – unlockWithCondition: (page 287) Relinquishes the lock and sets the receiver’s condition. Accessor Methods – setName: (page 286) Assigns a name to the receiver. – name (page 285) Returns the name associated with the receiver. NSConditionLock Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 282Instance Methods condition Returns the condition associated with the receiver. - (NSInteger)condition Return Value The condition associated with the receiver. If no condition has been set, returns 0. Availability Available in iOS 2.0 and later. Declared in NSLock.h initWithCondition: Initializes a newly allocated NSConditionLock object and sets its condition. - (id)initWithCondition:(NSInteger)condition Parameters condition The user-defined condition for the lock. The value of condition is user-defined; see the class description for more information. Return Value An initialized condition lock object; may be different than the original receiver. Availability Available in iOS 2.0 and later. Declared in NSLock.h lockBeforeDate: Attempts to acquire a lock before a specified moment in time. - (BOOL)lockBeforeDate:(NSDate *)limit NSConditionLock Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 283Parameters limit The date by which the lock must be acquired or the attempt will time out. Return Value YES if the lock is acquired within the time limit, NO otherwise. Discussion The condition associated with the receiver isn’t taken into account in this operation. This method blocks the thread’s execution until the receiver acquires the lock or limit is reached. Availability Available in iOS 2.0 and later. See Also – lockWhenCondition:beforeDate: (page 285) Declared in NSLock.h lockWhenCondition: Attempts to acquire a lock. - (void)lockWhenCondition:(NSInteger)condition Parameters condition The condition to match on. Discussion The receiver’s condition must be equal to condition before the locking operation will succeed. This method blocks the thread’s execution until the lock can be acquired. Availability Available in iOS 2.0 and later. See Also – lockWhenCondition:beforeDate: (page 285) – unlockWithCondition: (page 287) Declared in NSLock.h NSConditionLock Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 284lockWhenCondition:beforeDate: Attempts to acquire a lock before a specified moment in time. - (BOOL)lockWhenCondition:(NSInteger)condition beforeDate:(NSDate *)limit Parameters condition The condition to match on. limit The date by which the lock must be acquired or the attempt will time out. Return Value YES if the lock is acquired within the time limit, NO otherwise. Discussion The receiver’s condition must be equal to condition before the locking operation will succeed. This method blocks the thread’s execution until the lock can be acquired or limit is reached. Availability Available in iOS 2.0 and later. See Also – lockBeforeDate: (page 283) – lockWhenCondition: (page 284) Declared in NSLock.h name Returns the name associated with the receiver. - (NSString *)name Return Value The name of the receiver. Availability Available in iOS 2.0 and later. See Also – setName: (page 286) NSConditionLock Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 285Declared in NSLock.h setName: Assigns a name to the receiver. - (void)setName:(NSString *)newName Parameters newName The new name for the receiver. This method makes a copy of the specified string. Discussion You can use a name string to identify a condition lock within your code. Cocoa also uses this name as part of any error descriptions involving the receiver. Availability Available in iOS 2.0 and later. See Also – name (page 285) Declared in NSLock.h tryLock Attempts to acquire a lock without regard to the receiver’s condition. - (BOOL)tryLock Return Value YES if the lock could be acquired, NO otherwise. Discussion This method returns immediately. Availability Available in iOS 2.0 and later. See Also – tryLockWhenCondition: (page 287) NSConditionLock Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 286Declared in NSLock.h tryLockWhenCondition: Attempts to acquire a lock if the receiver’s condition is equal to the specified condition. - (BOOL)tryLockWhenCondition:(NSInteger)condition Return Value YES if the lock could be acquired, NO otherwise. Discussion As part of its implementation, this method invokes lockWhenCondition:beforeDate: (page 285). This method returns immediately. Availability Available in iOS 2.0 and later. See Also – tryLock (page 286) Declared in NSLock.h unlockWithCondition: Relinquishes the lock and sets the receiver’s condition. - (void)unlockWithCondition:(NSInteger)condition Parameters condition The user-defined condition for the lock. The value of condition is user-defined; see the class description for more information. Availability Available in iOS 2.0 and later. See Also – lockWhenCondition: (page 284) NSConditionLock Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 287Declared in NSLock.h NSConditionLock Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 288Inherits from NSMutableSet : NSSet : NSObject Conforms to NSCoding (NSSet) NSCopying (NSSet) NSMutableCopying (NSSet) NSFastEnumeration (NSSet) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSSet.h Companion guide Collections Programming Topics Overview The NSCountedSet class declares the programmatic interface to a mutable, unordered collection of indistinct objects. A counted set is also known as a bag. Each distinct object inserted into an NSCountedSet object has a counter associated with it. NSCountedSetkeeps track of the number of times objects are inserted and requires that objects be removed the same number of times. Thus, there is only one instance of an object in an NSSet object even if the object has been added to the set multiple times. The count (page 1473) method defined by the superclass NSSet has special significance; it returns the number of distinct objects, not the total number of times objects are represented in the set. The NSSet and NSMutableSet classes are provided for static and dynamic sets (respectively) whose elements are distinct. While NSCountedSet and CFBag are not toll-free bridged, they provide similar functionality. For more information on CFBag, consult the CFBag Reference. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 289 NSCountedSet Class ReferenceSubclassing Notes Because NSCountedSet is not a class cluster, it does not have primitive methods that provide the basis for its implementation. In general, there should be little need for subclassing. Methods to Override If you subclass NSCountedSet, you must override any method of which you want to change the behavior. If you change the primitive behavior of an NSCountedSet, for instance if you change how objects are stored, you must override all of the affected methods. These include: addObject: (page 291) removeObject: (page 294) objectEnumerator (page 294) countForObject: (page 291) If you change the primitive behavior, you must also override the primitive methods of NSSet and NSMutableSet. Tasks Initializing a Counted Set – initWithArray: (page 292) Returns a counted set object initialized with the contents of a given array. – initWithSet: (page 293) Returns a counted set object initialized with the contents of a given set. – initWithCapacity: (page 293) Returns a counted set object initialized with enough memory to hold a given number of objects. Adding and Removing Entries – addObject: (page 291) Adds a given object to the set. NSCountedSet Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 290– removeObject: (page 294) Removes a given object from the set. Examining a Counted Set – countForObject: (page 291) Returns the count associated with a given object in the set. – objectEnumerator (page 294) Returns an enumerator object that lets you access each object in the set once, independent of its count. Instance Methods addObject: Adds a given object to the set. - (void)addObject:(id)anObject Parameters anObject The object to add to the set. Discussion If anObject is already a member, addObject: increments the count associated with the object. If anObject is not already a member, it is sent a retain (page 2130) message. Availability Available in iOS 2.0 and later. Declared in NSSet.h countForObject: Returns the count associated with a given object in the set. - (NSUInteger)countForObject:(id)anObject NSCountedSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 291Parameters anObject The object for which to return the count. Return Value The count associated with anObject in the set, which can be thought of as the number of occurrences of anObject present in the set. Availability Available in iOS 2.0 and later. See Also count (page 1473) (NSSet) Declared in NSSet.h initWithArray: Returns a counted set object initialized with the contents of a given array. - (id)initWithArray:(NSArray *)anArray Parameters anArray An array of objects to add to the new set. Return Value An initialized counted set object with the contents of anArray. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. See Also initWithArray: (page 1477) (NSSet) setWithArray: (page 1467) (NSSet) Declared in NSSet.h NSCountedSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 292initWithCapacity: Returns a counted set object initialized with enough memory to hold a given number of objects. - (id)initWithCapacity:(NSUInteger)numItems Parameters numItems The initial capacity of the new counted set. Return Value A counted set object initialized with enough memory to hold numItems objects Discussion The method is the designated initializer for NSCountedSet. Note that the capacity is simply a hint to help initial memory allocation—the initial count of the object is 0, and the set still grows and shrinks as you add and remove objects. The hint is typically useful if the set will become large. Availability Available in iOS 2.0 and later. See Also initWithCapacity: (page 1022) (NSMutableSet) setWithCapacity: (page 1020) (NSMutableSet) Declared in NSSet.h initWithSet: Returns a counted set object initialized with the contents of a given set. - (id)initWithSet:(NSSet *)aSet Parameters aSet An set of objects to add to the new set. Return Value An initialized counted set object with the contents of aSet. The returned object might be different than the original receiver. NSCountedSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 293Availability Available in iOS 2.0 and later. See Also initWithSet: (page 1479) (NSSet) setWithSet: (page 1470) (NSSet) Declared in NSSet.h objectEnumerator Returns an enumerator object that lets you access each object in the set once, independent of its count. - (NSEnumerator *)objectEnumerator Return Value An enumerator object that lets you access each object in the set once, independent of its count. Discussion If you add a given object to the counted set multiple times, an enumeration of the set will produce that object only once. You shouldn’t modify the set during enumeration. If you intend to modify the set, use the allObjects (page 1472) method to create a “snapshot,” then enumerate the snapshot and modify the original set. Availability Available in iOS 2.0 and later. See Also nextObject (page 505) (NSEnumerator) Declared in NSSet.h removeObject: Removes a given object from the set. - (void)removeObject:(id)anObject NSCountedSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 294Parameters anObject The object to remove from the set. Discussion If anObject is present in the set, decrements the count associated with it. If the count is decremented to 0, anObject is removed from the set and sent a release (page 2128) message. removeObject: does nothing if anObject is not present in the set. Availability Available in iOS 2.0 and later. See Also – countForObject: (page 291) Declared in NSSet.h NSCountedSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 295Inherits from NSObject Conforms to NSCoding NSCopying NSMutableCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSData.h Foundation/NSSerialization.h (Deprecated) Companion guides Binary Data Programming Guide Property List Programming Guide Related sample code CryptoExercise EADemo LazyTableImages SeismicXML SimpleURLConnections Overview NSData and its mutable subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation objects. NSData creates static data objects, and NSMutableData creates dynamic data objects. NSData and NSMutableData are typically used for data storage and are also useful in Distributed Objects applications, where data contained in data objects can be copied or moved between applications. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 296 NSData Class ReferenceUsing 32-bit Cocoa, the size of the data is subject to a theoretical 2GB limit (in practice, because memory will be used by other objects this limit will be smaller); using 64-bit Cocoa, the size of the data is subject to a theoretical limit of about 8EB (in practice, the limit should not be a factor). NSData is “toll-free bridged” with its Core Foundation counterpart, CFDataRef. See “Toll-Free Bridging” for more information on toll-free bridging. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSMutableCopying mutableCopyWithZone: (page 2103) Tasks Creating Data Objects + data (page 300) Creates and returns an empty data object. + dataWithBytes:length: (page 300) Creates and returns a data object containing a given number of bytes copied from a given buffer. + dataWithBytesNoCopy:length: (page 301) Creates and returns a data object that holds length bytes from the buffer bytes. + dataWithBytesNoCopy:length:freeWhenDone: (page 302) Creates and returns a data object that holds a given number of bytes from a given buffer. + dataWithContentsOfFile: (page 302) Creates and returns a data object by reading every byte from the file specified by a given path. + dataWithContentsOfFile:options:error: (page 303) Creates and returns a data object by reading every byte from the file specified by a given path. + dataWithContentsOfURL: (page 305) Returns a data object containing the data from the location specified by a given URL. NSData Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 297+ dataWithContentsOfURL:options:error: (page 305) Creates and returns a data object containing the data from the location specified by aURL. + dataWithData: (page 306) Creates and returns a data object containing the contents of another data object. – initWithBytes:length: (page 310) Returns a data object initialized by adding to it a given number of bytes of data copied from a given buffer. – initWithBytesNoCopy:length: (page 310) Returns a data object initialized by adding to it a given number of bytes of data from a given buffer. – initWithBytesNoCopy:length:freeWhenDone: (page 311) Initializes a newly allocated data object by adding to it length bytes of data from the buffer bytes. – initWithContentsOfFile: (page 312) Returns a data object initialized by reading into it the data from the file specified by a given path. – initWithContentsOfFile:options:error: (page 312) Returns a data object initialized by reading into it the data from the file specified by a given path. – initWithContentsOfURL: (page 314) Initializes a newly allocated data object initialized with the data from the location specified by aURL. – initWithContentsOfURL:options:error: (page 314) Returns a data object initialized with the data from the location specified by a given URL. – initWithData: (page 315) Returns a data object initialized with the contents of another data object. + dataWithContentsOfMappedFile: (page 304) Deprecated in iOS 5.0 Creates and returns a data object from the mapped file specified by path. – initWithContentsOfMappedFile: (page 313) Deprecated in iOS 5.0 Returns a data object initialized by reading into it the mapped file specified by a given path. Accessing Data – bytes (page 307) Returns a pointer to the receiver’s contents. – description (page 307) Returns an NSString object that contains a hexadecimal representation of the receiver’s contents. – getBytes:length: (page 308) Copies a number of bytes from the start of the receiver's data into a given buffer. NSData Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 298– getBytes:range: (page 309) Copies a range of bytes from the receiver’s data into a given buffer. – subdataWithRange: (page 317) Returns a data object containing a copy of the receiver’s bytes that fall within the limits specified by a given range. – rangeOfData:options:range: (page 317) Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options. – getBytes: (page 308) Deprecated in iOS 4.0 Copies a data object’s contents into a given buffer. (Deprecated. This method is unsafe because it could potentially cause buffer overruns. You should use getBytes:length: (page 308) or getBytes:range: (page 309) instead.) Testing Data – isEqualToData: (page 316) Compares the receiving data object to otherData. – length (page 316) Returns the number of bytes contained in the receiver. Storing Data – writeToFile:atomically: (page 318) Writes the bytes in the receiver to the file specified by a given path. – writeToFile:options:error: (page 319) Writes the bytes in the receiver to the file specified by a given path. – writeToURL:atomically: (page 319) Writes the bytes in the receiver to the location specified by aURL. – writeToURL:options:error: (page 320) Writes the bytes in the receiver to the location specified by a given URL. NSData Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 299Class Methods data Creates and returns an empty data object. + (id)data Return Value An empty data object. Discussion This method is declared primarily for the use of mutable subclasses of NSData. Availability Available in iOS 2.0 and later. Related Sample Code EADemo LazyTableImages SeismicXML SimpleFTPSample XMLPerformance Declared in NSData.h dataWithBytes:length: Creates and returns a data object containing a given number of bytes copied from a given buffer. + (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length Parameters bytes A buffer containing data for the new object. length The number of bytes to copy from bytes. This value must not exceed the length of bytes. Return Value A data object containing length bytes copied from the buffer bytes. Returns nil if the data object could not be created. NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 300Availability Available in iOS 2.0 and later. See Also + dataWithBytesNoCopy:length: (page 301) + dataWithBytesNoCopy:length:freeWhenDone: (page 302) Related Sample Code CryptoExercise EADemo GKTank GLTextureAtlas PVRTextureLoader Declared in NSData.h dataWithBytesNoCopy:length: Creates and returns a data object that holds length bytes from the buffer bytes. + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length Parameters bytes A buffer containing data for the new object. bytes must point to a memory block allocated with malloc. length The number of bytes to hold from bytes. This value must not exceed the length of bytes. Return Value A data object that holds length bytes from the buffer bytes. Returns nil if the data object could not be created. Discussion The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc. Availability Available in iOS 2.0 and later. See Also + dataWithBytes:length: (page 300) + dataWithBytesNoCopy:length:freeWhenDone: (page 302) NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 301Declared in NSData.h dataWithBytesNoCopy:length:freeWhenDone: Creates and returns a data object that holds a given number of bytes from a given buffer. + (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeWhenDone Parameters bytes A buffer containing data for the new object. If freeWhenDone is YES, bytes must point to a memory block allocated with malloc. length The number of bytes to hold from bytes. This value must not exceed the length of bytes. freeWhenDone If YES, the returned object takes ownership of the bytes pointer and frees it on deallocation. Return Value A data object that holds length bytes from the buffer bytes. Returns nil if the data object could not be created. Availability Available in iOS 2.0 and later. See Also + dataWithBytes:length: (page 300) + dataWithBytesNoCopy:length: (page 301) Declared in NSData.h dataWithContentsOfFile: Creates and returns a data object by reading every byte from the file specified by a given path. + (id)dataWithContentsOfFile:(NSString *)path NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 302Parameters path The absolute path of the file from which to read data. Return Value A data object by reading every byte from the file specified by path. Returns nil if the data object could not be created. Discussion This method is equivalent to dataWithContentsOfFile:options:error: (page 303) with no options. If you need to know what was the reason for failure, use dataWithContentsOfFile:options:error: (page 303). A sample using this method can be found in “Working With Binary Data”. Availability Available in iOS 2.0 and later. See Also + dataWithContentsOfFile:options:error: (page 303) + dataWithContentsOfMappedFile: (page 304) Related Sample Code GLTextureAtlas MailComposer PhotoScroller PVRTextureLoader Declared in NSData.h dataWithContentsOfFile:options:error: Creates and returns a data object by reading every byte from the file specified by a given path. + (id)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr Parameters path The absolute path of the file from which to read data. mask A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions” (page 321). NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 303errorPtr If an error occurs, upon return contains an NSError object that describes the problem. Return Value A data object by reading every byte from the file specified by path. Returns nil if the data object could not be created. Availability Available in iOS 2.0 and later. Declared in NSData.h dataWithContentsOfMappedFile: Creates and returns a data object from the mapped file specified by path. (Deprecated in iOS 5.0.) + (id)dataWithContentsOfMappedFile:(NSString *)path Parameters path The absolute path of the file from which to read data. Return Value A data object from the mapped file specified by path. Returns nil if the data object could not be created. Discussion Because of file mapping restrictions, this method should only be used if the file is guaranteed to exist for the duration of the data object’s existence. It is generally safer to use the dataWithContentsOfFile: (page 302) method. This methods assumes mapped files are available from the underlying operating system. A mapped file uses virtual memory techniques to avoid copying pages of the file into memory until they are actually needed. Availability Available in iOS 2.0 and later. Deprecated in iOS 5.0. See Also + dataWithContentsOfFile: (page 302) Related Sample Code SimpleFTPSample NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 304SimpleNetworkStreams SimpleURLConnections Declared in NSData.h dataWithContentsOfURL: Returns a data object containing the data from the location specified by a given URL. + (id)dataWithContentsOfURL:(NSURL *)aURL Parameters aURL The URL from which to read data. Return Value A data object containing the data from the location specified by aURL. Returns nil if the data object could not be created. Discussion If you need to know what was the reason for failure, use dataWithContentsOfURL:options:error: (page 305). Availability Available in iOS 2.0 and later. See Also + dataWithContentsOfURL:options:error: (page 305) – initWithContentsOfURL: (page 314) Declared in NSData.h dataWithContentsOfURL:options:error: Creates and returns a data object containing the data from the location specified by aURL. + (id)dataWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr Parameters aURL The URL from which to read data. NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 305mask A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions” (page 321). errorPtr If there is an error reading in the data, upon return contains an NSError object that describes the problem. Availability Available in iOS 2.0 and later. See Also – initWithContentsOfURL: (page 314) Declared in NSData.h dataWithData: Creates and returns a data object containing the contents of another data object. + (id)dataWithData:(NSData *)aData Parameters aData A data object. Return Value A data object containing the contents of aData. Returns nil if the data object could not be created. Availability Available in iOS 2.0 and later. See Also – initWithData: (page 315) Declared in NSData.h NSData Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 306Instance Methods bytes Returns a pointer to the receiver’s contents. - (const void *)bytes Return Value A read-only pointer to the receiver’s contents. Discussion If the length (page 316) of the receiver is 0, this method returns nil. Availability Available in iOS 2.0 and later. See Also – description (page 307) – getBytes: (page 308) – getBytes:length: (page 308) – getBytes:range: (page 309) Related Sample Code CryptoExercise SimpleFTPSample SimpleNetworkStreams SimpleURLConnections Declared in NSData.h description Returns an NSString object that contains a hexadecimal representation of the receiver’s contents. - (NSString *)description Return Value An NSString object that contains a hexadecimal representation of the receiver’s contents in NSData property list format. Availability Available in iOS 2.0 and later. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 307See Also – bytes (page 307) – getBytes: (page 308) – getBytes:length: (page 308) – getBytes:range: (page 309) Declared in NSData.h getBytes: Copies a data object’s contents into a given buffer. (Deprecated in iOS 4.0. This method is unsafe because it could potentially cause buffer overruns. You should use getBytes:length: (page 308) or getBytes:range: (page 309) instead.) - (void)getBytes:(void *)buffer Parameters buffer A buffer into which to copy the receiver's data. The buffer must be at least length (page 316) bytes. Discussion You can see a sample using this method in “Working With Binary Data”. Availability Available in iOS 2.0 and later. Deprecated in iOS 4.0. See Also – bytes (page 307) – description (page 307) – getBytes:length: (page 308) – getBytes:range: (page 309) Declared in NSData.h getBytes:length: Copies a number of bytes from the start of the receiver's data into a given buffer. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 308- (void)getBytes:(void *)buffer length:(NSUInteger)length Parameters buffer A buffer into which to copy data. length The number of bytes from the start of the receiver's data to copy to buffer. Discussion The number of bytes copied is the smaller of the length parameter and the length of the data encapsulated in the object. Availability Available in iOS 2.0 and later. See Also – bytes (page 307) – description (page 307) – getBytes: (page 308) – getBytes:range: (page 309) Declared in NSData.h getBytes:range: Copies a range of bytes from the receiver’s data into a given buffer. - (void)getBytes:(void *)buffer range:(NSRange)range Parameters buffer A buffer into which to copy data. range The range of bytes in the receiver's data to copy to buffer. The range must lie within the range of bytes of the receiver's data. Discussion If range isn’t within the receiver’s range of bytes, an NSRangeException is raised. Availability Available in iOS 2.0 and later. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 309See Also – bytes (page 307) – description (page 307) – getBytes: (page 308) – getBytes:length: (page 308) Declared in NSData.h initWithBytes:length: Returns a data object initialized by adding to it a given number of bytes of data copied from a given buffer. - (id)initWithBytes:(const void *)bytes length:(NSUInteger)length Discussion A data object initialized by adding to it length bytes of data copied from the buffer bytes. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. See Also + dataWithBytes:length: (page 300) – initWithBytesNoCopy:length: (page 310) – initWithBytesNoCopy:length:freeWhenDone: (page 311) Related Sample Code CryptoExercise Declared in NSData.h initWithBytesNoCopy:length: Returns a data object initialized by adding to it a given number of bytes of data from a given buffer. - (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length Parameters bytes A buffer containing data for the new object. bytes must point to a memory block allocated with malloc. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 310length The number of bytes to hold from bytes. This value must not exceed the length of bytes. Return Value A data object initialized by adding to it length bytes of data from the buffer bytes. The returned object might be different than the original receiver. Discussion The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc. Availability Available in iOS 2.0 and later. See Also + dataWithBytes:length: (page 300) – initWithBytes:length: (page 310) – initWithBytesNoCopy:length:freeWhenDone: (page 311) Declared in NSData.h initWithBytesNoCopy:length:freeWhenDone: Initializes a newly allocated data object by adding to it length bytes of data from the buffer bytes. - (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)flag Parameters bytes A buffer containing data for the new object. If flag is YES, bytes must point to a memory block allocated with malloc. length The number of bytes to hold from bytes. This value must not exceed the length of bytes. flag If YES, the returned object takes ownership of the bytes pointer and frees it on deallocation. Availability Available in iOS 2.0 and later. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 311See Also + dataWithBytesNoCopy:length:freeWhenDone: (page 302) – initWithBytes:length: (page 310) – initWithBytesNoCopy:length: (page 310) Declared in NSData.h initWithContentsOfFile: Returns a data object initialized by reading into it the data from the file specified by a given path. - (id)initWithContentsOfFile:(NSString *)path Parameters path The absolute path of the file from which to read data. Return Value A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver. Discussion This method is equivalent to initWithContentsOfFile:options:error: (page 312) with no options. Availability Available in iOS 2.0 and later. See Also + dataWithContentsOfFile: (page 302) – initWithContentsOfMappedFile: (page 313) Declared in NSData.h initWithContentsOfFile:options:error: Returns a data object initialized by reading into it the data from the file specified by a given path. - (id)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 312Parameters path The absolute path of the file from which to read data. mask A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions” (page 321). errorPtr If an error occurs, upon return contains an NSError object that describes the problem. Return Value A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. See Also + dataWithContentsOfFile:options:error: (page 303) Declared in NSData.h initWithContentsOfMappedFile: Returns a data object initialized by reading into it the mapped file specified by a given path. (Deprecated in iOS 5.0.) - (id)initWithContentsOfMappedFile:(NSString *)path Parameters path The absolute path of the file from which to read data. Return Value A data object initialized by reading into it the mapped file specified by path. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. Deprecated in iOS 5.0. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 313See Also + dataWithContentsOfMappedFile: (page 304) – initWithContentsOfFile: (page 312) Declared in NSData.h initWithContentsOfURL: Initializes a newly allocated data object initialized with the data from the location specified by aURL. - (id)initWithContentsOfURL:(NSURL *)aURL Parameters aURL The URL from which to read data Return Value An NSData object initialized with the data from the location specified by aURL. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. See Also + dataWithContentsOfURL: (page 305) Declared in NSData.h initWithContentsOfURL:options:error: Returns a data object initialized with the data from the location specified by a given URL. - (id)initWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr Parameters aURL The URL from which to read data. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 314mask A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions” (page 321). errorPtr If there is an error reading in the data, upon return contains an NSError object that describes the problem. Return Value A data object initialized with the data from the location specified by aURL. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. See Also + dataWithContentsOfURL:options:error: (page 305) Declared in NSData.h initWithData: Returns a data object initialized with the contents of another data object. - (id)initWithData:(NSData *)data Parameters data A data object. Return Value A data object initialized with the contents data. The returned object might be different than the original receiver. Availability Available in iOS 2.0 and later. See Also + dataWithData: (page 306) Declared in NSData.h NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 315isEqualToData: Compares the receiving data object to otherData. - (BOOL)isEqualToData:(NSData *)otherData Parameters otherData The data object with which to compare the receiver. Return Value YES if the contents of otherData are equal to the contents of the receiver, otherwise NO. Discussion Two data objects are equal if they hold the same number of bytes, and if the bytes at the same position in the objects are the same. Availability Available in iOS 2.0 and later. Declared in NSData.h length Returns the number of bytes contained in the receiver. - (NSUInteger)length Return Value The number of bytes contained in the receiver. Availability Available in iOS 2.0 and later. Related Sample Code CryptoExercise GLPaint SimpleFTPSample SimpleNetworkStreams SimpleURLConnections Declared in NSData.h NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 316rangeOfData:options:range: Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options. - (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRange Parameters dataToFind The data for which to search. This value must not be nil. Important Raises an NSInvalidArgumentException (page 2292) if dataToFind is nil. mask A mask specifying search options. The “NSDataSearchOptions” (page 324) options may be specified singly or by combining them with the C bitwise OR operator. searchRange The range within the receiver in which to search for dataToFind. If this range is not within the receiver’s range of bytes, an NSRangeException (page 2292) raised. Return Value An NSRange (page 2260) structure giving the location and length of dataToFind within searchRange, modulo the options in mask. The range returned is relative to the start of the searched data, not the passed-in search range. Returns {NSNotFound, 0} if dataToFind is not found or is empty (@""). Availability Available in iOS 4.0 and later. Declared in NSData.h subdataWithRange: Returns a data object containing a copy of the receiver’s bytes that fall within the limits specified by a given range. - (NSData *)subdataWithRange:(NSRange)range Parameters range The range in the receiver from which to copy bytes. The range must not exceed the bounds of the receiver. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 317Return Value A data object containing a copy of the receiver’s bytes that fall within the limits specified by range. Discussion If range isn’t within the receiver’s range of bytes, an NSRangeException is raised. A sample using this method can be found in “Working With Binary Data”. Availability Available in iOS 2.0 and later. Related Sample Code EADemo Declared in NSData.h writeToFile:atomically: Writes the bytes in the receiver to the file specified by a given path. - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag Parameters path The location to which to write the receiver's bytes. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath (page 1634) before invoking this method. atomically If YES, the data is written to a backup file, and then—assuming no errors occur—the backup file is renamed to the name specified by path; otherwise, the data is written directly to path. Return Value YES if the operation succeeds, otherwise NO. Availability Available in iOS 2.0 and later. See Also – writeToURL:atomically: (page 319) Declared in NSData.h NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 318writeToFile:options:error: Writes the bytes in the receiver to the file specified by a given path. - (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr Parameters path The location to which to write the receiver's bytes. mask A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions” (page 322). errorPtr If there is an error writing out the data, upon return contains an NSError object that describes the problem. Return Value YES if the operation succeeds, otherwise NO. Availability Available in iOS 2.0 and later. See Also – writeToURL:options:error: (page 320) Declared in NSData.h writeToURL:atomically: Writes the bytes in the receiver to the location specified by aURL. - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)atomically Parameters aURL The location to which to write the receiver's bytes. Only file:// URLs are supported. atomically If YES, the data is written to a backup location, and then—assuming no errors occur—the backup location is renamed to the name specified by aURL; otherwise, the data is written directly to aURL. atomically is ignored if aURL is not of a type the supports atomic writes. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 319Return Value YES if the operation succeeds, otherwise NO. Discussion Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:atomically: (page 318), except for the type of the first argument. Availability Available in iOS 2.0 and later. See Also – writeToFile:atomically: (page 318) Declared in NSData.h writeToURL:options:error: Writes the bytes in the receiver to the location specified by a given URL. - (BOOL)writeToURL:(NSURL *)aURL options:(NSDataWritingOptions)mask error:(NSError **)errorPtr Parameters aURL The location to which to write the receiver's bytes. mask A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions” (page 322). errorPtr If there is an error writing out the data, upon return contains an NSError object that describes the problem. Return Value YES if the operation succeeds, otherwise NO. Discussion Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:options:error: (page 319), except for the type of the first argument. NSData Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 320Availability Available in iOS 2.0 and later. See Also – writeToFile:options:error: (page 319) Declared in NSData.h Constants NSDataReadingOptions Options for methods used to read NSData objects. enum { NSDataReadingMappedIfSafe = 1UL << 0, NSDataReadingUncached = 1UL << 1, NSDataReadingMappedAlways = 1UL << 3, }; typedef NSUInteger NSDataReadingOptions; Constants NSDataReadingMappedIfSafe A hint indicating the file should be mapped into virtual memory, if possible and safe. Available in iOS 5.0 and later. Declared in NSData.h. NSDataReadingUncached A hint indicating the file should not be stored in the file-system caches. For data being read once and discarded, this option can improve performance. Available in iOS 4.0 and later. Declared in NSData.h. NSDataReadingMappedAlways Hint to map the file in if possible. This takes precedence over NSDataReadingMappedIfSafe (page 321) if both are given. Available in iOS 5.0 and later. Declared in NSData.h. NSData Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 321Legacy Reading Options Deprecated names for reading options. Do not use these names, use the new replacements instead. enum { NSDataReadingMapped = NSDataReadingMappedIfSafe, NSMappedRead = NSDataReadingMapped, NSUncachedRead = NSDataReadingUncached }; Constants NSDataReadingMapped Deprecated name for NSDataReadingMappedIfSafe (page 321). Available in iOS 4.0 and later. Declared in NSData.h. NSMappedRead Deprecated name for NSDataReadingMapped (page 322). Available in iOS 2.0 and later. Declared in NSData.h. NSUncachedRead Deprecated name for NSDataReadingUncached (page 321). Available in iOS 2.0 and later. Declared in NSData.h. NSDataWritingOptions Options for methods used to write NSData objects. NSData Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 322enum { NSDataWritingAtomic = 1UL << 0, NSDataWritingFileProtectionNone = 0x10000000, NSDataWritingFileProtectionComplete = 0x20000000, NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000, NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000, NSDataWritingFileProtectionMask = 0xf0000000, }; typedef NSUInteger NSDataWritingOptions; Constants NSDataWritingAtomic A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES. Available in iOS 4.0 and later. Declared in NSData.h. NSDataWritingFileProtectionNone A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked. Available in iOS 4.0 and later. Declared in NSData.h. NSDataWritingFileProtectionComplete A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure. Available in iOS 4.0 and later. Declared in NSData.h. NSDataWritingFileProtectionCompleteUnlessOpen A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed. Available in iOS 5.0 and later. Declared in NSData.h. NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete (page 323). Available in iOS 5.0 and later. Declared in NSData.h. NSData Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 323NSDataWritingFileProtectionMask A mask to use when determining the file protection options assigned to the data. Available in iOS 4.0 and later. Declared in NSData.h. Legacy Writing Options Deprecated names for writing options. Do not use these names, use the new replacements instead. enum { NSAtomicWrite = NSDataWritingAtomic }; Constants NSAtomicWrite Deprecated name for NSDataWritingAtomic (page 323). Available in iOS 2.0 and later. Declared in NSData.h. NSDataSearchOptions Options for method used to search NSData objects. These options are used with the rangeOfData:options:range: (page 317) method. enum { NSDataSearchBackwards = 1UL << 0, NSDataSearchAnchored = 1UL << 1 }; typedef NSUInteger NSDataSearchOptions; Constants NSDataSearchBackwards Search from the end of NSData object. Available in iOS 4.0 and later. Declared in NSData.h. NSData Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 324NSDataSearchAnchored Search is limited to start (or end, if NSDataSearchBackwards) of NSData object. This option performs searching only on bytes at the beginning or end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of bytes occurs elsewhere in the data object. Available in iOS 4.0 and later. Declared in NSData.h. NSData Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 325Inherits from NSRegularExpression : NSObject Conforms to NSCoding (NSRegularExpression) NSCopying (NSRegularExpression) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 4.0 and later. Declared in Foundation/NSRegularExpression.h Overview The NSDataDetector class is a specialized subclass of the NSRegularExpression class designed to match data detectors. Currently the NSDataDetector class can match dates, addresses, links, phone numbers and transit information. The results of matching content is returned as NSTextCheckingResult objects. However, the NSTextCheckingResult objects returned by NSDataDetector are different from those returned by the base class NSRegularExpression. Results returned by NSDataDetector will be of one of the data detectors types, depending on the type of result being returned, and they will have corresponding properties. For example, results of type NSTextCheckingTypeDate (page 1683) have a date (page 1665), timeZone, and duration; results of type NSTextCheckingTypeLink (page 1683) have a URL (page 1670), and so forth. Examples The following shows several graduated examples of using the NSDataDetector class. This code fragment creates a data detector that will find URL links and phone numbers. If an error was encountered it is returned in error. NSError *error = NULL; 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 326 NSDataDetector Class ReferenceNSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber error:&error]; Once the data detector instance is created you can determine the number of matches within a range of a string using the NSRegularExpression method numberOfMatchesInString:options:range: (page 1418). NSUInteger numberOfMatches = [detector numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])]; If you are interested only in the overall range of the first match, the numberOfMatchesInString:options:range: (page 1418) method provides it. However, with data detectors, this is less likely than with regular expressions, because clients usually will be interested in additional information as well. The additional information available depends on the type of the result. For results of type NSTextCheckingTypeLink (page 1683), it is the URL property that is significant. For results of type NSTextCheckingTypePhoneNumber (page 1684), it is the phoneNumber (page 1667) property instead. The matchesInString:options:range: (page 1417) method is similar to the firstMatchInString:options:range: (page 1415), except that it returns all matches rather than only the first. The following code fragment finds all the matches for links and phone numbers in a string. NSArray *matches = [detector matchesInString:string options:0 range:NSMakeRange(0, [string length])]; for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match range]; if ([match resultType] == NSTextCheckingTypeLink) { NSURL *url = [match URL]; } else if ([match resultType] == NSTextCheckingTypePhoneNumber) { NSString *phoneNumber = [match phoneNumber]; } } NSDataDetector Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 327The NSRegularExpression Block object enumerator is the most general and flexible of the matching methods. It allows you to iterate through matches in a string, performing arbitrary actions on each as specified by the code in the Block, and to stop partway through if desired. In the following code fragment, the iteration is stopped after a certain number of matches have been found. __block NSUInteger count = 0; [detector enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ NSRange matchRange = [match range]; if ([match resultType] == NSTextCheckingTypeLink) { NSURL *url = [match URL]; } else if ([match resultType] == NSTextCheckingTypePhoneNumber) { NSString *phoneNumber = [match phoneNumber]; } if (++count >= 100) *stop = YES; }]; Tasks Creating Data Detector Instances + dataDetectorWithTypes:error: (page 329) Creates and returns a new data detector instance. – initWithTypes:error: (page 330) Initializes and returns a data detector instance. Getting the Checking Types checkingTypes (page 329) property Returns the checking types for this data detector. (read-only) NSDataDetector Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 328Properties For more about Objective-C properties, see “Properties” in The Objective-C Programming Language. checkingTypes Returns the checking types for this data detector. (read-only) @property(readonly) NSTextCheckingTypes checkingTypes Discussion The supported subset of checking types are specified in NSTextCheckingType (page 1682). Those constants can be combined using the C-bitwise OR operator. Currently, the supported data detectors checkingTypes are: NSTextCheckingTypeDate (page 1683), NSTextCheckingTypeAddress (page 1683), NSTextCheckingTypeLink (page 1683), NSTextCheckingTypePhoneNumber (page 1684), and NSTextCheckingTypeTransitInformation (page 1684). Availability Available in iOS 4.0 and later. Declared in NSRegularExpression.h Class Methods dataDetectorWithTypes:error: Creates and returns a new data detector instance. + (NSDataDetector *)dataDetectorWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error Parameters checkingTypes The checking types. The supported checking types are a subset of the types specified in NSTextCheckingType (page 1682). Those constants can be combined using the C-bitwise OR operator. error An out parameter that if an error occurs during initialization contains the encountered error. NSDataDetector Class Reference Properties 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 329Return Value Returns the newly initialized data detector. If an error was encountered returns nil, and error contains the error. Discussion Currently, the supported data detectors checkingTypes are: NSTextCheckingTypeDate (page 1683), NSTextCheckingTypeAddress (page 1683), NSTextCheckingTypeLink (page 1683), NSTextCheckingTypePhoneNumber (page 1684), and NSTextCheckingTypeTransitInformation (page 1684). Availability Available in iOS 4.0 and later. See Also – initWithTypes:error: (page 330) @property checkingTypes (page 329) Declared in NSRegularExpression.h Instance Methods initWithTypes:error: Initializes and returns a data detector instance. - (id)initWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error Parameters checkingTypes The checking types. The supported checking types are a subset of the types NSTextCheckingType (page 1682). Those constants can be combined using the C-bitwise OR operator. error An out parameter that if an error occurs during initialization contains the encountered error. Return Value Returns the newly initialized data detector. If an error was encountered returns nil, and error contains the error. NSDataDetector Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 330Discussion Currently, the supported data detectors checkingTypes are: NSTextCheckingTypeDate (page 1683), NSTextCheckingTypeAddress (page 1683), NSTextCheckingTypeLink (page 1683), NSTextCheckingTypePhoneNumber (page 1684), and NSTextCheckingTypeTransitInformation (page 1684). Availability Available in iOS 4.0 and later. See Also + dataDetectorWithTypes:error: (page 329) @property checkingTypes (page 329) Declared in NSRegularExpression.h NSDataDetector Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 331Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSDate.h Companion guides Date and Time Programming Guide Property List Programming Guide Related sample code DateSectionTitles International Mountains TableViewSuite URLCache XMLPerformance Overview NSDate objects represent a single point in time. NSDate is a class cluster; its single public superclass, NSDate, declares the programmatic interface for specific and relative time values. The objects you create using NSDate are referred to as date objects. They are immutable objects. Because of the nature of class clusters, objects returned by the NSDate class are instances not of that abstract class but of one of its private subclasses. Although a date object’s class is private, its interface is public, as declared by the abstract superclass NSDate. Generally, you instantiate a suitable date object by invoking one of the date... class methods. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 332 NSDate Class ReferenceNSDate is an abstract class that provides behavior for creating dates, comparing dates, representing dates, computing intervals, and similar functionality. NSDate presents a programmatic interface through which suitable date objects are requested and returned. Date objects returned from NSDate are lightweight and immutable since they represent an invariant point in time. This class is designed to provide the foundation for arbitrary calendrical representations. The sole primitive method of NSDate, timeIntervalSinceReferenceDate (page 351), provides the basis for all the other methods in the NSDate interface. This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT. To parse strings containing dates and to generate string representations of a date, you should use an instance of NSDateFormatter using the methods dateFromString: (page 388) and stringFromDate: (page 419) respectively—see “Date Formatters” for more details. NSDate models the change from the Julian to the Gregorian calendar in October 1582, and calendrical calculations performed in conjunction with NSCalendar take this transition into account. Note, however, that some locales adopted the Gregorian calendar at other times; for example, Great Britain didn't switch over until September 1752. NSDate is “toll-free bridged” with its Cocoa Foundation counterpart, CFDateRef. See “Toll-Free Bridging” for more information on toll-free bridging. Subclassing Notes The major reason for subclassing NSDate is to create a class with convenience methods for working with a particular calendrical system. But you could also require a custom NSDate class for other reasons, such as to get a date and time value that provides a finer temporal granularity. Methods to Override If you want to subclass NSDate to obtain behavior different than that provided by the private or public subclasses, you must do these things: ● Declare a suitable instance variable to hold the date and time value (relative to an absolute reference date). ● Override the timeIntervalSinceReferenceDate (page 351) instance method to provide the correct date and time value based on your instance variable. ● Override initWithTimeIntervalSinceReferenceDate: (page 348), the designated initializer method. If you are creating a subclass that represents a calendrical system, you must also define methods that partition past and future periods into the units of this calendar. NSDate Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 333Because the NSDate class adopts the NSCopying and NSCoding protocols, your subclass must also implement all of the methods in these protocols. Special Considerations Your subclass may use a different reference date than the absolute reference date used by NSDate (the first instance of 1 January 2001, GMT). If it does, it must still use the absolute reference date in its implementations of the methods timeIntervalSinceReferenceDate (page 351) and initWithTimeIntervalSinceReferenceDate: (page 348). That is, the reference date referred to in the titles of these methods is the absolute reference date. If you do not use the absolute reference date in these methods, comparisons between NSDate objects of your subclass and NSDate objects of a private subclass will not work. Tasks Creating and Initializing Date Objects + date (page 336) Creates and returns a new date set to the current date and time. + dateWithTimeIntervalSinceNow: (page 338) Creates and returns an NSDate object set to a given number of seconds from the current date and time. + dateWithTimeInterval:sinceDate: (page 337) Creates and returns an NSDate object set to a given number of seconds from the specified date. + dateWithTimeIntervalSinceReferenceDate: (page 339) Creates and returns an NSDate object set to a given number of seconds from the first instant of 1 January 2001, GMT. + dateWithTimeIntervalSince1970: (page 338) Creates and returns an NSDate object set to the given number of seconds from the first instant of 1 January 1970, GMT. – init (page 345) Returns an NSDate object initialized to the current date and time. – initWithTimeIntervalSinceNow: (page 347) Returns an NSDate object initialized relative to the current date and time by a given number of seconds. – initWithTimeInterval:sinceDate: (page 346) Returns an NSDate object initialized relative to another given date by a given number of seconds. NSDate Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 334– initWithTimeIntervalSinceReferenceDate: (page 348) Returns an NSDate object initialized relative the first instant of 1 January 2001, GMT by a given number of seconds. – initWithTimeIntervalSince1970: (page 347) Returns an NSDate object set to the given number of seconds from the first instant of 1 January 1970, GMT. Getting Temporal Boundaries + distantFuture (page 339) Creates and returns an NSDate object representing a date in the distant future. + distantPast (page 340) Creates and returns an NSDate object representing a date in the distant past. Comparing Dates – isEqualToDate: (page 348) Returns a Boolean value that indicates whether a given object is an NSDate object and exactly equal the receiver. – earlierDate: (page 345) Returns the earlier of the receiver and another given date. – laterDate: (page 349) Returns the later of the receiver and another given date. – compare: (page 342) Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date. Getting Time Intervals – timeIntervalSinceDate: (page 350) Returns the interval between the receiver and another given date. – timeIntervalSinceNow (page 351) Returns the interval between the receiver and the current date and time. NSDate Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 335+ timeIntervalSinceReferenceDate (page 341) Returns the interval between the first instant of 1 January 2001, GMT and the current date and time. – timeIntervalSinceReferenceDate (page 351) Returns the interval between the receiver and the first instant of 1 January 2001, GMT. – timeIntervalSince1970 (page 350) Returns the interval between the receiver and the first instant of 1 January 1970, GMT. Adding a Time Interval – dateByAddingTimeInterval: (page 343) Returns a new NSDate object that is set to a given number of seconds relative to the receiver. – addTimeInterval: (page 341) Deprecated in iOS 4.0 Returns a new NSDate object that is set to a given number of seconds relative to the receiver. (Deprecated. This method has been replaced by dateByAddingTimeInterval: (page 343).) Representing Dates as Strings – description (page 344) Returns a string representation of the receiver. – descriptionWithLocale: (page 344) Returns a string representation of the receiver using the given locale. Class Methods date Creates and returns a new date set to the current date and time. + (id)date Return Value A new date object set to the current date and time. Discussion This method uses the default initializer method for the class, init (page 345). NSDate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 336The following code sample shows how to use date to get the current date: NSDate *today = [NSDate date]; Availability Available in iOS 2.0 and later. Related Sample Code Birthdays GKTank SimpleEKDemo SimpleUndo TableViewSuite Declared in NSDate.h dateWithTimeInterval:sinceDate: Creates and returns an NSDate object set to a given number of seconds from the specified date. + (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date Parameters seconds The number of seconds to add to date. Use a negative argument to specify a date and time before date. date The date. Return Value An NSDate object set to seconds seconds from date. Availability Available in iOS 4.0 and later. Declared in NSDate.h NSDate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 337dateWithTimeIntervalSince1970: Creates and returns an NSDate object set to the given number of seconds from the first instant of 1 January 1970, GMT. + (id)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds Parameters seconds The number of seconds from the reference date, 1 January 1970, GMT, for the new date. Use a negative argument to specify a date before this date. Return Value An NSDate object set to seconds seconds from the reference date. Discussion This method is useful for creating NSDate objects from time_t values returned by BSD system functions. Availability Available in iOS 2.0 and later. See Also – timeIntervalSince1970 (page 350) Declared in NSDate.h dateWithTimeIntervalSinceNow: Creates and returns an NSDate object set to a given number of seconds from the current date and time. + (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)seconds Parameters seconds The number of seconds from the current date and time for the new date. Use a negative value to specify a date before the current date. Return Value An NSDate object set to seconds seconds from the current date and time. Availability Available in iOS 2.0 and later. NSDate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 338See Also – initWithTimeIntervalSinceNow: (page 347) Related Sample Code SimpleEKDemo Declared in NSDate.h dateWithTimeIntervalSinceReferenceDate: Creates and returns an NSDate object set to a given number of seconds from the first instant of 1 January 2001, GMT. + (id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds Parameters seconds The number of seconds from the absolute reference date (the first instant of 1 January 2001, GMT) for the new date. Use a negative argument to specify a date and time before the reference date. Return Value An NSDate object set to seconds seconds from the absolute reference date. Availability Available in iOS 2.0 and later. See Also – initWithTimeIntervalSinceReferenceDate: (page 348) Related Sample Code URLCache Declared in NSDate.h distantFuture Creates and returns an NSDate object representing a date in the distant future. + (id)distantFuture Return Value An NSDate object representing a date in the distant future (in terms of centuries). NSDate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 339Discussion You can pass this value when an NSDate object is required to have the date argument essentially ignored. For example, the NSWindow method nextEventMatchingMask:untilDate:inMode:dequeue: returns nil if an event specified in the event mask does not happen before the specified date. You can use the object returned by distantFuture as the date argument to wait indefinitely for the event to occur. myEvent = [myWindow nextEventMatchingMask:myEventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; Availability Available in iOS 2.0 and later. See Also + distantPast (page 340) Related Sample Code XMLPerformance Declared in NSDate.h distantPast Creates and returns an NSDate object representing a date in the distant past. + (id)distantPast Return Value An NSDate object representing a date in the distant past (in terms of centuries). Discussion You can use this object as a control date, a guaranteed temporal boundary. Availability Available in iOS 2.0 and later. See Also + distantFuture (page 339) NSDate Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 340Declared in NSDate.h timeIntervalSinceReferenceDate Returns the interval between the first instant of 1 January 2001, GMT and the current date and time. + (NSTimeInterval)timeIntervalSinceReferenceDate Return Value The interval between the system’s absolute reference date (the first instant of 1 January 2001, GMT) and the current date and time. Discussion This method is the primitive method for NSDate. If you subclass NSDate, you must override this method with your own implementation for it. Availability Available in iOS 2.0 and later. See Also – timeIntervalSinceReferenceDate (page 351) – timeIntervalSinceDate: (page 350) – timeIntervalSince1970 (page 350) – timeIntervalSinceNow (page 351) Declared in NSDate.h Instance Methods addTimeInterval: Returns a new NSDate object that is set to a given number of seconds relative to the receiver. (Deprecated in iOS 4.0. This method has been replaced by dateByAddingTimeInterval: (page 343).) - (id)addTimeInterval:(NSTimeInterval)seconds NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 341Parameters seconds The number of seconds to add to the receiver. Use a negative value for seconds to have the returned object specify a date before the receiver. Return Value A new NSDate object that is set to seconds seconds relative to the receiver. The date returned might have a representation different from the receiver’s. Availability Available in iOS 2.0 and later. Deprecated in iOS 4.0. See Also – initWithTimeInterval:sinceDate: (page 346) – timeIntervalSinceDate: (page 350) – dateByAddingTimeInterval: (page 343) Declared in NSDate.h compare: Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date. - (NSComparisonResult)compare:(NSDate *)anotherDate Parameters anotherDate The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X. Return Value If: ● The receiver and anotherDate are exactly equal to each other, NSOrderedSame ● The receiver is later in time than anotherDate, NSOrderedDescending ● The receiver is earlier in time than anotherDate, NSOrderedAscending. NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 342Discussion This method detects sub-second differences between dates. If you want to compare dates with a less fine granularity, use timeIntervalSinceDate: (page 350) to compare the two dates. Availability Available in iOS 2.0 and later. See Also – earlierDate: (page 345) isEqual: (page 2122) (NSObject protocol) – laterDate: (page 349) Declared in NSDate.h dateByAddingTimeInterval: Returns a new NSDate object that is set to a given number of seconds relative to the receiver. - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds Parameters seconds The number of seconds to add to the receiver. Use a negative value for seconds to have the returned object specify a date before the receiver. Return Value A new NSDate object that is set to seconds seconds relative to the receiver. The date returned might have a representation different from the receiver’s. Availability Available in iOS 4.0 and later. See Also – initWithTimeInterval:sinceDate: (page 346) – timeIntervalSinceDate: (page 350) Related Sample Code TableViewSuite Declared in NSDate.h NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 343description Returns a string representation of the receiver. - (NSString *)description Return Value A string representation of the receiver. Discussion The representation is not guaranteed to remain constant across different releases of the operating system. To format a date, you should use a date formatter object instead (see NSDateFormatter and Data Formatting Guide) Availability Available in iOS 2.0 and later. See Also – descriptionWithLocale: (page 344) Declared in NSDate.h descriptionWithLocale: Returns a string representation of the receiver using the given locale. - (NSString *)descriptionWithLocale:(id)locale Parameters locale An NSLocale object. If you pass nil, NSDate formats the date in the same way as the description (page 344) method. On Mac OS X v10.4 and earlier, this parameter was an NSDictionary object. If you pass in an NSDictionary object on Mac OS X v10.5, NSDate uses the default user locale—the same as if you passed in [NSLocale currentLocale]. Return Value A string representation of the receiver, using the given locale, or if the locale argument is nil, in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”) NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 344Special Considerations On Mac OS X v10.4 and earlier, localeDictionary is an NSDictionary object containing locale data. To use the user's preferences, you can use [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]. Availability Available in iOS 4.0 and later. Declared in NSDate.h earlierDate: Returns the earlier of the receiver and another given date. - (NSDate *)earlierDate:(NSDate *)anotherDate Parameters anotherDate The date with which to compare the receiver. Return Value The earlier of the receiver and anotherDate, determined using timeIntervalSinceDate: (page 350). If the receiver and anotherDate represent the same date, returns the receiver. Availability Available in iOS 2.0 and later. See Also – compare: (page 342) isEqual: (page 2122) (NSObject protocol) – laterDate: (page 349) Declared in NSDate.h init Returns an NSDate object initialized to the current date and time. - (id)init NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 345Return Value An NSDate object initialized to the current date and time. Discussion This method uses the designated initializer, initWithTimeIntervalSinceReferenceDate: (page 348). Availability Available in iOS 2.0 and later. See Also + date (page 336) – initWithTimeIntervalSinceReferenceDate: (page 348) Declared in NSDate.h initWithTimeInterval:sinceDate: Returns an NSDate object initialized relative to another given date by a given number of seconds. - (id)initWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)refDate Parameters seconds The number of seconds to add to refDate. A negative value means the receiver will be earlier than refDate. refDate The reference date. Return Value An NSDate object initialized relative to refDate by seconds seconds. Discussion This method uses the designated initializer, initWithTimeIntervalSinceReferenceDate: (page 348). Availability Available in iOS 2.0 and later. Declared in NSDate.h NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 346initWithTimeIntervalSince1970: Returns an NSDate object set to the given number of seconds from the first instant of 1 January 1970, GMT. - (id)initWithTimeIntervalSince1970:(NSTimeInterval)seconds Parameters seconds The number of seconds from the reference date, 1 January 1970, GMT, for the new date. Use a negative argument to specify a date before this date. Return Value An NSDate object set to seconds seconds from the reference date. Discussion This method is useful for creating NSDate objects from time_t values returned by BSD system functions. Availability Available in iOS 4.0 and later. Declared in NSDate.h initWithTimeIntervalSinceNow: Returns an NSDate object initialized relative to the current date and time by a given number of seconds. - (id)initWithTimeIntervalSinceNow:(NSTimeInterval)seconds Parameters seconds The number of seconds from relative to the current date and time to which the receiver should be initialized. A negative value means the returned object will represent a date in the past. Return Value An NSDate object initialized relative to the current date and time by seconds seconds. Discussion This method uses the designated initializer, initWithTimeIntervalSinceReferenceDate: (page 348). Availability Available in iOS 2.0 and later. NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 347See Also + dateWithTimeIntervalSinceNow: (page 338) Declared in NSDate.h initWithTimeIntervalSinceReferenceDate: ReturnsanNSDateobjectinitializedrelativethefirstinstantof1January2001,GMTbyagivennumberofseconds. - (id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds Parameters seconds The number of seconds to add to the reference date (the first instant of 1 January 2001, GMT). A negative value means the receiver will be earlier than the reference date. Return Value An NSDate object initialized relative to the absolute reference date by seconds seconds. Discussion This method is the designated initializer for the NSDate class and is declared primarily for the use of subclasses of NSDate. When you subclass NSDate to create a concrete date class, you must override this method. Availability Available in iOS 2.0 and later. See Also + dateWithTimeIntervalSinceReferenceDate: (page 339) Declared in NSDate.h isEqualToDate: Returns a Boolean value that indicates whether a given object is an NSDate object and exactly equal the receiver. - (BOOL)isEqualToDate:(NSDate *)anotherDate Parameters anotherDate The date to compare with the receiver. NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 348Return Value YES if the anotherDate is an NSDate object and is exactly equal to the receiver, otherwise NO. Discussion This method detects sub-second differences between dates. If you want to compare dates with a less fine granularity, use timeIntervalSinceDate: (page 350) to compare the two dates. Availability Available in iOS 2.0 and later. See Also – compare: (page 342) – earlierDate: (page 345) isEqual: (page 2122) (NSObject protocol) – laterDate: (page 349) Declared in NSDate.h laterDate: Returns the later of the receiver and another given date. - (NSDate *)laterDate:(NSDate *)anotherDate Parameters anotherDate The date with which to compare the receiver. Return Value The later of the receiver and anotherDate, determined using timeIntervalSinceDate: (page 350). If the receiver and anotherDate represent the same date, returns the receiver. Availability Available in iOS 2.0 and later. See Also – compare: (page 342) – earlierDate: (page 345) isEqual: (page 2122) (NSObject protocol) Declared in NSDate.h NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 349timeIntervalSince1970 Returns the interval between the receiver and the first instant of 1 January 1970, GMT. - (NSTimeInterval)timeIntervalSince1970 Return Value The interval between the receiver and the reference date, 1 January 1970, GMT. If the receiver is earlier than the reference date, the value is negative. Availability Available in iOS 2.0 and later. See Also – timeIntervalSinceDate: (page 350) – timeIntervalSinceNow (page 351) – timeIntervalSinceReferenceDate (page 351) + timeIntervalSinceReferenceDate (page 341) Declared in NSDate.h timeIntervalSinceDate: Returns the interval between the receiver and another given date. - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate Parameters anotherDate The date with which to compare the receiver. Return Value The interval between the receiver and anotherDate. If the receiver is earlier than anotherDate, the return value is negative. Availability Available in iOS 2.0 and later. See Also – timeIntervalSince1970 (page 350) – timeIntervalSinceNow (page 351) – timeIntervalSinceReferenceDate (page 351) NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 350Declared in NSDate.h timeIntervalSinceNow Returns the interval between the receiver and the current date and time. - (NSTimeInterval)timeIntervalSinceNow Return Value The interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative. Availability Available in iOS 2.0 and later. See Also – timeIntervalSinceDate: (page 350) – timeIntervalSince1970 (page 350) – timeIntervalSinceReferenceDate (page 351) Declared in NSDate.h timeIntervalSinceReferenceDate Returns the interval between the receiver and the first instant of 1 January 2001, GMT. - (NSTimeInterval)timeIntervalSinceReferenceDate Return Value The interval between the receiver and the system’s absolute reference date (the first instant of 1 January 2001, GMT). If the receiver is earlier than the reference date, the value is negative. Availability Available in iOS 2.0 and later. See Also – timeIntervalSinceDate: (page 350) – timeIntervalSinceNow (page 351) + timeIntervalSinceReferenceDate (page 341) Related Sample Code XMLPerformance NSDate Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 351Declared in NSDate.h Constants NSTimeIntervalSince1970 NSDate provides a constant that specifies the number of seconds from 1 January 1970 to the reference date, 1 January 2001. #define NSTimeIntervalSince1970 978307200.0 Constants NSTimeIntervalSince1970 The number of seconds from 1 January 1970 to the reference date, 1 January 2001. Available in iOS 2.0 and later. Declared in NSDate.h. Discussion 1 January 1970 is the epoch (or starting point) for Unix time. Declared in NSDate.h Notifications NSSystemClockDidChangeNotification Posted whenever the system clock is changed. This can be initiated by a call to settimeofday() or the user changing values in the Date and Time Preference panel. The notification object is null. This notification does not contain a userInfo dictionary. Availability Available in iOS 4.0 and later. Declared in NSDate.h NSDate Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 352Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSCalendar.h Companion guide Date and Time Programming Guide Related sample code Birthdays DateSectionTitles TableViewSuite Overview NSDateComponents encapsulates the components of a date in an extendable, object-oriented manner. It is used to specify a date by providing the temporal components that make up a date and time: hour, minutes, seconds, day, month, year, and so on. It can also be used to specify a duration of time, for example, 5 hours and 16 minutes. An NSDateComponents object is not required to define all the component fields. When a new instance of NSDateComponents is created the date components are set to NSUndefinedDateComponent. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 353 NSDateComponents Class ReferenceImportant An NSDateComponents object is meaningless in itself; you need to know what calendar it is interpreted against, and you need to know whether the values are absolute values of the units, or quantities of the units. An instance of NSDateComponents is not responsible for answering questions about a date beyond the information with which it was initialized. For example, if you initialize one with May 6, 2004, its weekday is NSUndefinedDateComponent, not Thursday. To get the correct day of the week, you must create a suitable instance of NSCalendar, create an NSDate object using dateFromComponents: and then use components:fromDate: to retrieve the weekday—as illustrated in the following example. NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:6]; [comps setMonth:5]; [comps setYear:2004]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *date = [gregorian dateFromComponents:comps]; [comps release]; NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date]; int weekday = [weekdayComponents weekday]; For more details, see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Tasks Getting Information About an NSDateComponents Object – era (page 358) Returns the number of era units for the receiver. – year (page 373) Returns the number of year units for the receiver. – month (page 360) Returns the number of month units for the receiver. NSDateComponents Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 354– date (page 357) Returns the date of the receiver. – day (page 357) Returns the number of day units for the receiver. – hour (page 359) Returns the number of hour units for the receiver. – minute (page 359) Returns the number of minute units for the receiver. – second (page 361) Returns the number of second units for the receiver. – week (page 371) Returns the number of week units for the receiver. – weekday (page 371) Returns the number of weekday units for the receiver. – weekdayOrdinal (page 372) Returns the ordinal number of weekday units for the receiver. – quarter (page 360) Returns the number of quarters in the calendar. – calendar (page 357) Returns the calendar of the receiver. – timeZone (page 370) Returns the receiver’s time zone. – weekOfMonth (page 372) Returns the week of the month. – weekOfYear (page 373) Returns the week of the year. – yearForWeekOfYear (page 374) Returns the year for the week of the year. Setting Information for an NSDateComponents Object – setEra: (page 362) Sets the number of era units for the receiver. NSDateComponents Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 355– setYear: (page 369) Sets the number of year units for the receiver. – setMonth: (page 364) Sets the number of month units for the receiver. – setDay: (page 362) Sets the number of day units for the receiver. – setHour: (page 363) Sets the number of hour units for the receiver. – setMinute: (page 363) Sets the number of minute units for the receiver. – setSecond: (page 365) Sets the number of second units for the receiver. – setWeek: (page 366) Sets the number of week units for the receiver. – setWeekday: (page 367) Sets the number of weekday units for the receiver. – setWeekdayOrdinal: (page 367) Sets the ordinal number of weekday units for the receiver. – setQuarter: (page 364) Sets the number of quarters in the calendar. – setCalendar: (page 361) Sets the receiver’s calendar. – setTimeZone: (page 365) Sets the receiver’s time zone. – setWeekOfMonth: (page 368) Sets the week of the month. – setWeekOfYear: (page 368) Sets the week of the year. – setYearForWeekOfYear: (page 369) Sets the year for the week of the year. NSDateComponents Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 356Instance Methods calendar Returns the calendar of the receiver. - (NSCalendar *)calendar Return Value The calendar. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 4.0 and later. See Also – setCalendar: (page 361) Declared in NSCalendar.h date Returns the date of the receiver. - (NSDate *)date Return Value The date. Availability Available in iOS 4.0 and later. Declared in NSCalendar.h day Returns the number of day units for the receiver. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 357- (NSInteger)day Return Value The number of day units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setDay: (page 362) Related Sample Code Birthdays DateSectionTitles Declared in NSCalendar.h era Returns the number of era units for the receiver. - (NSInteger)era Return Value The number of era units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setEra: (page 362) Declared in NSCalendar.h NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 358hour Returns the number of hour units for the receiver. - (NSInteger)hour Return Value The number of hour units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setHour: (page 363) Related Sample Code TableViewSuite Declared in NSCalendar.h minute Returns the number of minute units for the receiver. - (NSInteger)minute Return Value The number of minute units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setMinute: (page 363) NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 359Declared in NSCalendar.h month Returns the number of month units for the receiver. - (NSInteger)month Return Value The number of month units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setMonth: (page 364) Related Sample Code DateSectionTitles Declared in NSCalendar.h quarter Returns the number of quarters in the calendar. - (NSInteger)quarter Return Value The number of quarters units for the receiver. Availability Available in iOS 4.0 and later. Declared in NSCalendar.h NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 360second Returns the number of second units for the receiver. - (NSInteger)second Return Value The number of second units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setSecond: (page 365) Declared in NSCalendar.h setCalendar: Sets the receiver’s calendar. - (void)setCalendar:(NSCalendar *)cal Parameters cal The calendar. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 4.0 and later. See Also – calendar (page 357) Declared in NSCalendar.h NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 361setDay: Sets the number of day units for the receiver. - (void)setDay:(NSInteger)v Parameters v The number of day units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – day (page 357) Related Sample Code DateSectionTitles Declared in NSCalendar.h setEra: Sets the number of era units for the receiver. - (void)setEra:(NSInteger)v Parameters v The number of era units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 362See Also – era (page 358) Declared in NSCalendar.h setHour: Sets the number of hour units for the receiver. - (void)setHour:(NSInteger)v Parameters v The number of hour units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – hour (page 359) Declared in NSCalendar.h setMinute: Sets the number of minute units for the receiver. - (void)setMinute:(NSInteger)v Parameters v The number of minute units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 363Availability Available in iOS 2.0 and later. See Also – minute (page 359) Related Sample Code TableViewSuite Declared in NSCalendar.h setMonth: Sets the number of month units for the receiver. - (void)setMonth:(NSInteger)v Parameters v The number of month units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – month (page 360) Declared in NSCalendar.h setQuarter: Sets the number of quarters in the calendar. - (void)setQuarter:(NSInteger)v NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 364Parameters v The number of quarters units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 4.0 and later. Declared in NSCalendar.h setSecond: Sets the number of second units for the receiver. - (void)setSecond:(NSInteger)v Parameters v The number of second units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – second (page 361) Related Sample Code TableViewSuite Declared in NSCalendar.h setTimeZone: Sets the receiver’s time zone. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 365- (void)setTimeZone:(NSTimeZone *)tz Parameters tz The time zone. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 4.0 and later. See Also – timeZone (page 370) Declared in NSCalendar.h setWeek: Sets the number of week units for the receiver. - (void)setWeek:(NSInteger)v Parameters v The number of week units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – week (page 371) Declared in NSCalendar.h NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 366setWeekday: Sets the number of weekday units for the receiver. - (void)setWeekday:(NSInteger)v Parameters v The number of weekday units for the receiver. Discussion Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1. This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – weekday (page 371) Declared in NSCalendar.h setWeekdayOrdinal: Sets the ordinal number of weekday units for the receiver. - (void)setWeekdayOrdinal:(NSInteger)v Parameters v The ordinal number of weekday units for the receiver. Discussion Weekday ordinal units represent the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month. This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 367Availability Available in iOS 2.0 and later. See Also – weekdayOrdinal (page 372) Declared in NSCalendar.h setWeekOfMonth: Sets the week of the month. - (void)setWeekOfMonth:(NSInteger)week Parameters week The week number of the month. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 5.0 and later. See Also – weekOfMonth (page 372) Declared in NSCalendar.h setWeekOfYear: Sets the week of the year. - (void)setWeekOfYear:(NSInteger)week Parameters week The week number of the year. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 368Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 5.0 and later. See Also – weekOfYear (page 373) Declared in NSCalendar.h setYear: Sets the number of year units for the receiver. - (void)setYear:(NSInteger)v Parameters v The number of year units for the receiver. Discussion This value will be interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – year (page 373) Related Sample Code DateSectionTitles Declared in NSCalendar.h setYearForWeekOfYear: Sets the year for the week of the year. - (void)setYearForWeekOfYear:(NSInteger)year NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 369Parameters year The year when the calendar is being interpreted as a week-based calendar. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 5.0 and later. See Also – yearForWeekOfYear (page 374) – firstWeekday (page 201) (NSCalendar Class Reference) – minimumDaysInFirstWeek (page 203) (NSCalendar Class Reference) Declared in NSCalendar.h timeZone Returns the receiver’s time zone. - (NSTimeZone *)timeZone Return Value The time zone. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 4.0 and later. See Also – setTimeZone: (page 365) Declared in NSCalendar.h NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 370week Returns the number of week units for the receiver. - (NSInteger)week Return Value The number of week units for the receiver. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setWeek: (page 366) Declared in NSCalendar.h weekday Returns the number of weekday units for the receiver. - (NSInteger)weekday Return Value The number of weekday units for the receiver. Discussion Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1. This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setWeekday: (page 367) NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 371Related Sample Code Birthdays TableViewSuite Declared in NSCalendar.h weekdayOrdinal Returns the ordinal number of weekday units for the receiver. - (NSInteger)weekdayOrdinal Return Value The ordinal number of weekday units for the receiver. Discussion Weekday ordinal units represent the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month. This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setWeekdayOrdinal: (page 367) Declared in NSCalendar.h weekOfMonth Returns the week of the month. - (NSInteger)weekOfMonth Return Value The week number of the month. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 372Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 5.0 and later. See Also – setWeekOfMonth: (page 368) Declared in NSCalendar.h weekOfYear Returns the week of the year. - (NSInteger)weekOfYear Return Value The week number of the year. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 5.0 and later. Declared in NSCalendar.h year Returns the number of year units for the receiver. - (NSInteger)year Return Value The number of year units for the receiver. NSDateComponents Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 373Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 2.0 and later. See Also – setYear: (page 369) Related Sample Code DateSectionTitles Declared in NSCalendar.h yearForWeekOfYear Returns the year for the week of the year. - (NSInteger)yearForWeekOfYear Return Value The year number for the week of the year. Discussion This value is interpreted in the context of the calendar with which it is used—see “Calendars, Date Components, and Calendar Units” in Date and Time Programming Guide. Availability Available in iOS 5.0 and later. Declared in NSCalendar.h Constants NSDateComponents undefined component identifier This constant specifies that an NSDateComponents component is undefined. NSDateComponents Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 374enum { NSUndefinedDateComponent = 0x7fffffff }; Constants NSUndefinedDateComponent Specifies that the component is undefined. Available in iOS 2.0 and later. Declared in NSCalendar.h. Declared in NSCalendar.h NSDateComponents Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 375Inherits from NSFormatter : NSObject Conforms to NSCoding (NSFormatter) NSCopying (NSFormatter) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSDateFormatter.h Companion guide Data Formatting Guide Related sample code LocateMe SeismicXML SimpleUndo TableViewSuite XMLPerformance Overview Instances of NSDateFormatter create string representations of NSDate (and NSCalendarDate) objects, and convert textual representations of dates and times into NSDate objects. You can express the representation of dates and times flexibly using pre-set format styles or custom format strings. There are many attributes you can get and set on a 10.4-style date formatter, including the locale, time zone, calendar, format string, and the various textual strings like the month names. You are encouraged, however, not to change individual settings. Instead you should accept the default settings established on initialization and specify the format using setDateStyle: (page 398), setTimeStyle: (page 410), and appropriate style constants (see NSDateFormatterStyle (page 424)—these are styles that the user can configure in the International preferences panel in System Preferences). NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 376 NSDateFormatter Class Reference[dateFormatter setTimeStyle:NSDateFormatterNoStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800]; NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; [dateFormatter setLocale:usLocale]; NSLog(@"Date for locale %@: %@", [[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]); // Output: // Date for locale en_US: Jan 2, 2001 NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"]; [dateFormatter setLocale:frLocale]; NSLog(@"Date for locale %@: %@", [[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]); // Output: // Date for locale fr_FR: 2 janv. 2001 Note that although setting a format string (setDateFormat: (page 397)) in principle specifies an exact format, in practice it may nevertheless also be overridden by a user’s preferences—see Data Formatting Guide for more details. Formatter Behaviors and OS Versions With Mac OS X v10.4 and later, NSDateFormatter has two modes of operation (or behaviors). See Data Formatting Guide for a full description of the old and new behaviors. iOS Note iOS supports only the 10.4+ behavior. 10.0-style methods and format strings are not available on iOS. By default, on Mac OS X v10.4 instances of NSDateFormatter have the same behavior as they did on Mac OS X versions 10.0 to 10.3. On Mac OS X v10.5 and later, NSDateFormatter defaults to the 10.4+ behavior. However, if you initialize a formatter using initWithDateFormat:allowNaturalLanguage:, you are (for backwards NSDateFormatter Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 377compatibility reasons) creating an “old-style” date formatter. Tousethenewbehavior,youinitializetheformatter with init. If necessary, you can set the default class behavior using setDefaultFormatterBehavior: (page 387), or you can set the behavior for an instance using setFormatterBehavior: (page 400) message with the argument NSDateFormatterBehavior10_4. By default, the 10.4-style formatter returns NSDate objects (prior to Mac OS X v10.4, date formatters returned NSCalendarDate objects). You can change this behavior using setGeneratesCalendarDates: (page 401), although this is strongly discouraged (as NSCalendarDate is deprecated on Mac OS X v10.6 and later). Tasks Converting Objects – dateFromString: (page 388) Returns a date representation of a given string interpreted using the receiver’s current settings. – stringFromDate: (page 419) Returns a string representation of a given date formatted using the receiver’s current settings. + localizedStringFromDate:dateStyle:timeStyle: (page 386) Returns string representation of a given date formatted for the current locale using the specified date and time styles. – getObjectValue:forString:range:error: (page 392) Returns by reference a date representation of a given string and the range of the string used, and returns a Boolean value that indicates whether the string could be parsed. – generatesCalendarDates (page 391) Returns a Boolean value that indicates whether the receiver generates calendar dates. – setGeneratesCalendarDates: (page 401) Sets whether the receiver generates calendar dates. Managing Formats and Styles – dateFormat (page 388) Returns the date format string used by the receiver. – setDateFormat: (page 397) Sets the date format for the receiver. NSDateFormatter Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 378– dateStyle (page 389) Returns the date style of the receiver. – setDateStyle: (page 398) Sets the date style of the receiver. – timeStyle (page 419) Returns the time style of the receiver. – setTimeStyle: (page 410) Sets the time style of the receiver. + dateFormatFromTemplate:options:locale: (page 383) Returns a localized date format string representing the given date format components arranged appropriately for the specified locale. Managing Attributes – calendar (page 388) Returns the calendar for the receiver. – setCalendar: (page 396) Sets the calendar for the receiver. – defaultDate (page 390) Returns the default date for the receiver. – setDefaultDate: (page 398) Sets the default date for the receiver. – locale (page 394) Returns the locale for the receiver. – setLocale: (page 402) Sets the locale for the receiver. – timeZone (page 420) Returns the time zone for the receiver. – setTimeZone: (page 410) Sets the time zone for the receiver. – twoDigitStartDate (page 420) Returns the earliest date that can be denoted by a two-digit year specifier. – setTwoDigitStartDate: (page 411) Sets the two-digit start date for the receiver. NSDateFormatter Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 379– gregorianStartDate (page 393) Returns the start date of the Gregorian calendar for the receiver. – setGregorianStartDate: (page 401) Sets the start date of the Gregorian calendar for the receiver. Managing Behavior Version – formatterBehavior (page 391) Returns the formatter behavior for the receiver. – setFormatterBehavior: (page 400) Sets the formatter behavior for the receiver. + defaultFormatterBehavior (page 385) Returns the default formatting behavior for instances of the class. + setDefaultFormatterBehavior: (page 387) Sets the default formatting behavior for instances of the class. Managing Natural Language Support – isLenient (page 393) Returns a Boolean value that indicates whether the receiver uses heuristics when parsing a string. – setLenient: (page 401) Sets whether the receiver uses heuristics when parsing a string. – doesRelativeDateFormatting (page 390) Returns a Boolean value that indicates whether the receiver uses phrases such as “today” and “tomorrow” for the date component. – setDoesRelativeDateFormatting: (page 399) Specifies whether the receiver uses phrases such as “today” and “tomorrow” for the date component. Managing AM and PM Symbols – AMSymbol (page 387) Returns the AM symbol for the receiver. NSDateFormatter Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 380– setAMSymbol: (page 396) Sets the AM symbol for the receiver. – PMSymbol (page 395) Returns the PM symbol for the receiver. – setPMSymbol: (page 404) Sets the PM symbol for the receiver. Managing Weekday Symbols – weekdaySymbols (page 423) Returns the array of weekday symbols for the receiver. – setWeekdaySymbols: (page 413) Sets the weekday symbols for the receiver. – shortWeekdaySymbols (page 416) Returns the array of short weekday symbols for the receiver. – setShortWeekdaySymbols: (page 407) Sets the short weekday symbols for the receiver. – veryShortWeekdaySymbols (page 422) Returns the array of very short weekday symbols for the receiver. – setVeryShortWeekdaySymbols: (page 413) Sets the vert short weekday symbols for the receiver – standaloneWeekdaySymbols (page 418) Returns the array of standalone weekday symbols for the receiver. – setStandaloneWeekdaySymbols: (page 409) Sets the standalone weekday symbols for the receiver. – shortStandaloneWeekdaySymbols (page 416) Returns the array of short standalone weekday symbols for the receiver. – setShortStandaloneWeekdaySymbols: (page 407) Sets the short standalone weekday symbols for the receiver. – veryShortStandaloneWeekdaySymbols (page 422) Returns the array of very short standalone weekday symbols for the receiver. – setVeryShortStandaloneWeekdaySymbols: (page 412) Sets the very short standalone weekday symbols for the receiver. NSDateFormatter Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 381Managing Month Symbols – monthSymbols (page 394) Returns the month symbols for the receiver. – setMonthSymbols: (page 403) Sets the month symbols for the receiver. – shortMonthSymbols (page 414) Returns the array of short month symbols for the receiver. – setShortMonthSymbols: (page 405) Sets the short month symbols for the receiver. – veryShortMonthSymbols (page 421) Returns the very short month symbols for the receiver. – setVeryShortMonthSymbols: (page 411) Sets the very short month symbols for the receiver. – standaloneMonthSymbols (page 417) Returns the standalone month symbols for the receiver. – setStandaloneMonthSymbols: (page 408) Sets the standalone month symbols for the receiver. – shortStandaloneMonthSymbols (page 415) Returns the short standalone month symbols for the receiver. – setShortStandaloneMonthSymbols: (page 406) Sets the short standalone month symbols for the receiver. – veryShortStandaloneMonthSymbols (page 421) Returns the very short month symbols for the receiver. – setVeryShortStandaloneMonthSymbols: (page 412) Sets the very short standalone month symbols for the receiver. Managing Quarter Symbols – quarterSymbols (page 395) Returns the quarter symbols for the receiver. – setQuarterSymbols: (page 404) Sets the quarter symbols for the receiver. NSDateFormatter Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 382– shortQuarterSymbols (page 414) Returns the short quarter symbols for the receiver. – setShortQuarterSymbols: (page 405) Sets the short quarter symbols for the receiver. – standaloneQuarterSymbols (page 418) Returns the standalone quarter symbols for the receiver. – setStandaloneQuarterSymbols: (page 408) Sets the standalone quarter symbols for the receiver. – shortStandaloneQuarterSymbols (page 415) Returns the short standalone quarter symbols for the receiver. – setShortStandaloneQuarterSymbols: (page 406) Sets the short standalone quarter symbols for the receiver. Managing Era Symbols – eraSymbols (page 391) Returns the era symbols for the receiver. – setEraSymbols: (page 400) Sets the era symbols for the receiver. – longEraSymbols (page 394) Returns the long era symbols for the receiver – setLongEraSymbols: (page 403) Sets the long era symbols for the receiver. Class Methods dateFormatFromTemplate:options:locale: Returns a localized date format string representing the given date format components arranged appropriately for the specified locale. + (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale NSDateFormatter Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 383Parameters template A string containing date format patterns (such as “MM” or “h”). For full details, see Unicode Technical Standard #35. opts No options are currently defined—pass 0. locale The locale for which the template is required. Return Value A localized date format string representing the date format components given in template, arranged appropriately for the locale specified by locale. The returned string may not contain exactly those components given in template, but may—for example—have locale-specific adjustments applied. Discussion Different locales have different conventions for the ordering of date components. You use this method to get an appropriate format string for a given set of components for a specified locale (typically you use the current locale—see currentLocale (page 861)). The following example shows the difference between the date formats for British and American English: NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; NSString *dateFormat; NSString *dateComponents = @"yMMMMd"; dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale]; NSLog(@"Date format for %@: %@", [usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat); dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale]; NSLog(@"Date format for %@: %@", NSDateFormatter Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 384[gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat); // Output: // Date format for English (United States): MMMM d, y // Date format for English (United Kingdom): d MMMM y Availability Available in iOS 4.0 and later. Declared in NSDateFormatter.h defaultFormatterBehavior Returns the default formatting behavior for instances of the class. + (NSDateFormatterBehavior)defaultFormatterBehavior Return Value The default formatting behavior for instances of the class. For possible values, see NSDateFormatterBehavior (page 425). Discussion For iOS and for Mac OS X applications linked against Leopard (Mac OS X v10.5) and later, the default is NSDateFormatterBehavior10_4. Availability Available in iOS 2.0 and later. See Also + setDefaultFormatterBehavior: (page 387). – formatterBehavior (page 391) – setFormatterBehavior: (page 400) Declared in NSDateFormatter.h NSDateFormatter Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 385localizedStringFromDate:dateStyle:timeStyle: Returns string representation of a given date formatted for the current locale using the specified date and time styles. + (NSString *)localizedStringFromDate:(NSDate *)date dateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle Parameters date A date. dateStyle A format style for the date. For possible values, see NSDateFormatterStyle (page 424). timeStyle A format style for the time. For possible values, see NSDateFormatterStyle (page 424). Return Value A localized string representation of date using the specified date and time styles Discussion This method uses a date formatter configured with the current default settings. The returned string is the same as if you configured and used a date formatter as shown in the following example: NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setFormatterBehavior:NSDateFormatterBehavior10_4]; [formatter setDateStyle:dateStyle]; [formatter setTimeStyle:timeStyle]; NSString *result = [formatter stringForObjectValue:date]; Availability Available in iOS 4.0 and later. See Also – stringFromDate: (page 419) Declared in NSDateFormatter.h NSDateFormatter Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 386setDefaultFormatterBehavior: Sets the default formatting behavior for instances of the class. + (void)setDefaultFormatterBehavior:(NSDateFormatterBehavior)behavior Parameters behavior The default formatting behavior for instances of the class. For possible values, see NSDateFormatterBehavior (page 425). Availability Available in iOS 2.0 and later. See Also + defaultFormatterBehavior (page 385) – formatterBehavior (page 391) – setFormatterBehavior: (page 400) Declared in NSDateFormatter.h Instance Methods AMSymbol Returns the AM symbol for the receiver. - (NSString *)AMSymbol Return Value The AM symbol for the receiver. Availability Available in iOS 2.0 and later. See Also – setAMSymbol: (page 396) – PMSymbol (page 395) – setPMSymbol: (page 404) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 387calendar Returns the calendar for the receiver. - (NSCalendar *)calendar Return Value The calendar for the receiver. Availability Available in iOS 2.0 and later. See Also – setCalendar: (page 396) Declared in NSDateFormatter.h dateFormat Returns the date format string used by the receiver. - (NSString *)dateFormat Return Value The date format string used by the receiver. Discussion See Data Formatting Guide for a list of the conversion specifiers permitted in date format strings. Availability Available in iOS 2.0 and later. See Also – setDateFormat: (page 397) Declared in NSDateFormatter.h dateFromString: Returns a date representation of a given string interpreted using the receiver’s current settings. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 388- (NSDate *)dateFromString:(NSString *)string Parameters string The string to parse. Return Value A date representation of string interpreted using the receiver’s current settings. Availability Available in iOS 2.0 and later. See Also – getObjectValue:forString:range:error: (page 392) – stringFromDate: (page 419) Related Sample Code URLCache Declared in NSDateFormatter.h dateStyle Returns the date style of the receiver. - (NSDateFormatterStyle)dateStyle Return Value The date style of the receiver. For possible values, see NSDateFormatterStyle (page 424). Availability Available in iOS 2.0 and later. See Also – setDateStyle: (page 398) Related Sample Code SimpleFTPSample Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 389defaultDate Returns the default date for the receiver. - (NSDate *)defaultDate Return Value The default date for the receiver. Discussion The default default date is nil. Availability Available in iOS 2.0 and later. See Also – setDefaultDate: (page 398) Declared in NSDateFormatter.h doesRelativeDateFormatting Returns a Boolean value that indicates whether the receiver uses phrases such as “today” and “tomorrow” for the date component. - (BOOL)doesRelativeDateFormatting Return Value YES if the receiver uses relative date formatting, otherwise NO. Discussion For a full discussion, see setDoesRelativeDateFormatting: (page 399). Availability Available in iOS 4.0 and later. See Also – setDoesRelativeDateFormatting: (page 399) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 390eraSymbols Returns the era symbols for the receiver. - (NSArray *)eraSymbols Return Value An array containing NSString objects representing the era symbols for the receiver (for example, {“B.C.E.”, “C.E.”}). Availability Available in iOS 2.0 and later. See Also – setEraSymbols: (page 400) – longEraSymbols (page 394) Declared in NSDateFormatter.h formatterBehavior Returns the formatter behavior for the receiver. - (NSDateFormatterBehavior)formatterBehavior Return Value The formatter behavior for the receiver. For possible values, see NSDateFormatterBehavior (page 425). Availability Available in iOS 2.0 and later. See Also + defaultFormatterBehavior (page 385). + setDefaultFormatterBehavior: (page 387) – setFormatterBehavior: (page 400) Declared in NSDateFormatter.h generatesCalendarDates Returns a Boolean value that indicates whether the receiver generates calendar dates. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 391- (BOOL)generatesCalendarDates Return Value YES if the receiver generates calendar dates, otherwise NO. Availability Available in iOS 2.0 and later. See Also – setGeneratesCalendarDates: (page 401) Declared in NSDateFormatter.h getObjectValue:forString:range:error: Returnsbyreferenceadaterepresentationofagivenstringandtherangeofthestringused,andreturnsaBoolean value that indicates whether the string could be parsed. - (BOOL)getObjectValue:(out id *)obj forString:(NSString *)string range:(inout NSRange *)rangep error:(out NSError **)error Parameters obj If the receiver is able to parse string, upon return contains a date representation of string. string The string to parse. rangep If the receiver is able to parse string, upon return contains the range of string used to create the date. error If the receiver is unable to create a date by parsing string, upon return contains an NSError object that describes the problem. Return Value YES if the receiver can create a date by parsing string, otherwise NO. Availability Available in iOS 2.0 and later. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 392See Also – dateFromString: (page 388) stringForObjectValue: (page 720) Declared in NSDateFormatter.h gregorianStartDate Returns the start date of the Gregorian calendar for the receiver. - (NSDate *)gregorianStartDate Return Value The start date of the Gregorian calendar for the receiver. Availability Available in iOS 2.0 and later. See Also – setGregorianStartDate: (page 401) Declared in NSDateFormatter.h isLenient Returns a Boolean value that indicates whether the receiver uses heuristics when parsing a string. - (BOOL)isLenient Return Value YES if the receiver has been set to use heuristics when parsing a string to guess at the date which is intended, otherwise NO. Availability Available in iOS 2.0 and later. See Also – setLenient: (page 401) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 393locale Returns the locale for the receiver. - (NSLocale *)locale Return Value The locale for the receiver. Availability Available in iOS 2.0 and later. See Also – setLocale: (page 402) Declared in NSDateFormatter.h longEraSymbols Returns the long era symbols for the receiver - (NSArray *)longEraSymbols Return Value An array containing NSString objects representing the era symbols for the receiver (for example, {“Before Common Era”, “Common Era”}). Availability Available in iOS 2.0 and later. See Also – setLongEraSymbols: (page 403) – eraSymbols (page 391) Declared in NSDateFormatter.h monthSymbols Returns the month symbols for the receiver. - (NSArray *)monthSymbols NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 394Return Value An array of NSString objects that specify the month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setMonthSymbols: (page 403) – shortMonthSymbols (page 414) – veryShortMonthSymbols (page 421) – standaloneMonthSymbols (page 417) – shortStandaloneMonthSymbols (page 415) – veryShortStandaloneMonthSymbols (page 421) Related Sample Code DateSectionTitles Declared in NSDateFormatter.h PMSymbol Returns the PM symbol for the receiver. - (NSString *)PMSymbol Return Value The PM symbol for the receiver. Availability Available in iOS 2.0 and later. See Also – setPMSymbol: (page 404) – AMSymbol (page 387) – setAMSymbol: (page 396) Declared in NSDateFormatter.h quarterSymbols Returns the quarter symbols for the receiver. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 395- (NSArray *)quarterSymbols Return Value An array containing NSString objects representing the quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setQuarterSymbols: (page 404) – shortQuarterSymbols (page 414) – standaloneQuarterSymbols (page 418) – shortStandaloneQuarterSymbols (page 415) Declared in NSDateFormatter.h setAMSymbol: Sets the AM symbol for the receiver. - (void)setAMSymbol:(NSString *)string Parameters string The AM symbol for the receiver. Availability Available in iOS 2.0 and later. See Also – AMSymbol (page 387) – PMSymbol (page 395) – setPMSymbol: (page 404) Declared in NSDateFormatter.h setCalendar: Sets the calendar for the receiver. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 396- (void)setCalendar:(NSCalendar *)calendar Parameters calendar The calendar for the receiver. Availability Available in iOS 2.0 and later. See Also – calendar (page 388) Related Sample Code DateSectionTitles Declared in NSDateFormatter.h setDateFormat: Sets the date format for the receiver. - (void)setDateFormat:(NSString *)string Parameters string The date format for the receiver. See Data Formatting Guide for a list of the conversion specifiers permitted in date format strings. Availability Available in iOS 2.0 and later. See Also – dateFormat (page 388). Related Sample Code TableViewSuite URLCache Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 397setDateStyle: Sets the date style of the receiver. - (void)setDateStyle:(NSDateFormatterStyle)style Parameters style The date style of the receiver. For possible values, see NSDateFormatterStyle (page 424). Availability Available in iOS 2.0 and later. See Also – dateStyle (page 389). Related Sample Code DateSectionTitles Locations PhotoLocations URLCache XMLPerformance Declared in NSDateFormatter.h setDefaultDate: Sets the default date for the receiver. - (void)setDefaultDate:(NSDate *)date Parameters date The default date for the receiver. Availability Available in iOS 2.0 and later. See Also – defaultDate (page 390) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 398setDoesRelativeDateFormatting: Specifies whether the receiver uses phrases such as “today” and “tomorrow” for the date component. - (void)setDoesRelativeDateFormatting:(BOOL)b Parameters b YES to specify that the receiver should use relative date formatting, otherwise NO. Discussion If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” or “tomorrow”—that indicates a relative date. The available phrases depend on the locale for the date formatter; whereas, for dates in the future, English may only allow “tomorrow,” French may allow “the day after the day after tomorrow,” as illustrated in the following example. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"]; [dateFormatter setLocale:frLocale]; [dateFormatter setDoesRelativeDateFormatting:YES]; NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3]; NSString *dateString = [dateFormatter stringFromDate:date]; NSLog(@"dateString: %@", dateString); // Output // dateString: après-après-demain Availability Available in iOS 4.0 and later. See Also – doesRelativeDateFormatting (page 390) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 399setEraSymbols: Sets the era symbols for the receiver. - (void)setEraSymbols:(NSArray *)array Parameters array An array containing NSString objects representing the era symbols for the receiver (for example, {“B.C.E.”, “C.E.”}). Availability Available in iOS 2.0 and later. See Also – eraSymbols (page 391) – longEraSymbols (page 394) Declared in NSDateFormatter.h setFormatterBehavior: Sets the formatter behavior for the receiver. - (void)setFormatterBehavior:(NSDateFormatterBehavior)behavior Parameters behavior The formatter behavior for the receiver. For possible values, see NSDateFormatterBehavior (page 425). Availability Available in iOS 2.0 and later. See Also + defaultFormatterBehavior (page 385). + setDefaultFormatterBehavior: (page 387) – formatterBehavior (page 391) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 400setGeneratesCalendarDates: Sets whether the receiver generates calendar dates. - (void)setGeneratesCalendarDates:(BOOL)b Parameters b A Boolean value that specifies whether the receiver generates calendar dates. Availability Available in iOS 2.0 and later. See Also – generatesCalendarDates (page 391). Declared in NSDateFormatter.h setGregorianStartDate: Sets the start date of the Gregorian calendar for the receiver. - (void)setGregorianStartDate:(NSDate *)date Parameters date The start date of the Gregorian calendar for the receiver. Availability Available in iOS 2.0 and later. See Also – gregorianStartDate (page 393) Declared in NSDateFormatter.h setLenient: Sets whether the receiver uses heuristics when parsing a string. - (void)setLenient:(BOOL)b NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 401Parameters b YES to use heuristics when parsing a string to guess at the date which is intended, otherwise NO. Discussion If a formatter is set to be lenient, when parsing a string it uses heuristics to guess at the date which is intended. As with any guessing, it may get the result date wrong (that is, a date other than that which was intended). Availability Available in iOS 2.0 and later. See Also – isLenient (page 393) Declared in NSDateFormatter.h setLocale: Sets the locale for the receiver. - (void)setLocale:(NSLocale *)locale Parameters locale The locale for the receiver. Availability Available in iOS 2.0 and later. See Also – locale (page 394) Related Sample Code URLCache XMLPerformance Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 402setLongEraSymbols: Sets the long era symbols for the receiver. - (void)setLongEraSymbols:(NSArray *)array Parameters array An array containing NSString objects representing the era symbols for the receiver (for example, {“Before Common Era”, “Common Era”}). Availability Available in iOS 2.0 and later. See Also – longEraSymbols (page 394) – eraSymbols (page 391) Declared in NSDateFormatter.h setMonthSymbols: Sets the month symbols for the receiver. - (void)setMonthSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – monthSymbols (page 394) – setShortMonthSymbols: (page 405) – setVeryShortMonthSymbols: (page 411) – setStandaloneMonthSymbols: (page 408) – setShortStandaloneMonthSymbols: (page 406) – setVeryShortStandaloneMonthSymbols: (page 412) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 403setPMSymbol: Sets the PM symbol for the receiver. - (void)setPMSymbol:(NSString *)string Parameters string The PM symbol for the receiver. Availability Available in iOS 2.0 and later. See Also – PMSymbol (page 395) – AMSymbol (page 387) – setAMSymbol: (page 396) Declared in NSDateFormatter.h setQuarterSymbols: Sets the quarter symbols for the receiver. - (void)setQuarterSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – quarterSymbols (page 395) – setShortQuarterSymbols: (page 405) – setStandaloneQuarterSymbols: (page 408) – setShortStandaloneQuarterSymbols: (page 406) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 404setShortMonthSymbols: Sets the short month symbols for the receiver. - (void)setShortMonthSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the short month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – shortMonthSymbols (page 414) – setMonthSymbols: (page 403) – setVeryShortMonthSymbols: (page 411) – setStandaloneMonthSymbols: (page 408) – setShortStandaloneMonthSymbols: (page 406) – setVeryShortStandaloneMonthSymbols: (page 412) Declared in NSDateFormatter.h setShortQuarterSymbols: Sets the short quarter symbols for the receiver. - (void)setShortQuarterSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the short quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – shortQuarterSymbols (page 414) – setQuarterSymbols: (page 404) – setStandaloneQuarterSymbols: (page 408) – setShortStandaloneQuarterSymbols: (page 406) NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 405Declared in NSDateFormatter.h setShortStandaloneMonthSymbols: Sets the short standalone month symbols for the receiver. - (void)setShortStandaloneMonthSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the short standalone month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – shortStandaloneMonthSymbols (page 415) – setMonthSymbols: (page 403) – setShortMonthSymbols: (page 405) – setVeryShortMonthSymbols: (page 411) – setStandaloneMonthSymbols: (page 408) – setVeryShortStandaloneMonthSymbols: (page 412) Declared in NSDateFormatter.h setShortStandaloneQuarterSymbols: Sets the short standalone quarter symbols for the receiver. - (void)setShortStandaloneQuarterSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the short standalone quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – shortStandaloneQuarterSymbols (page 415) NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 406– setQuarterSymbols: (page 404) – setShortQuarterSymbols: (page 405) – setStandaloneQuarterSymbols: (page 408) Declared in NSDateFormatter.h setShortStandaloneWeekdaySymbols: Sets the short standalone weekday symbols for the receiver. - (void)setShortStandaloneWeekdaySymbols:(NSArray *)array Parameters array An array of NSString objects that specify the short standalone weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – shortStandaloneWeekdaySymbols (page 416) – setWeekdaySymbols: (page 413) – setShortWeekdaySymbols: (page 407) – setVeryShortWeekdaySymbols: (page 413) – setStandaloneWeekdaySymbols: (page 409) – setVeryShortStandaloneWeekdaySymbols: (page 412) Declared in NSDateFormatter.h setShortWeekdaySymbols: Sets the short weekday symbols for the receiver. - (void)setShortWeekdaySymbols:(NSArray *)array Parameters array An array of NSString objects that specify the short weekday symbols for the receiver. Availability Available in iOS 2.0 and later. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 407See Also – shortWeekdaySymbols (page 416) – setWeekdaySymbols: (page 413) – setVeryShortWeekdaySymbols: (page 413) – setStandaloneWeekdaySymbols: (page 409) – setShortStandaloneWeekdaySymbols: (page 407) – setVeryShortStandaloneWeekdaySymbols: (page 412) Declared in NSDateFormatter.h setStandaloneMonthSymbols: Sets the standalone month symbols for the receiver. - (void)setStandaloneMonthSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the standalone month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – standaloneMonthSymbols (page 417) – setMonthSymbols: (page 403) – setShortMonthSymbols: (page 405) – setVeryShortMonthSymbols: (page 411) – setShortStandaloneMonthSymbols: (page 406) – setVeryShortStandaloneMonthSymbols: (page 412) Declared in NSDateFormatter.h setStandaloneQuarterSymbols: Sets the standalone quarter symbols for the receiver. - (void)setStandaloneQuarterSymbols:(NSArray *)array NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 408Parameters array An array of NSString objects that specify the standalone quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setStandaloneQuarterSymbols: (page 408) – setQuarterSymbols: (page 404) – setShortQuarterSymbols: (page 405) – setShortStandaloneQuarterSymbols: (page 406) Declared in NSDateFormatter.h setStandaloneWeekdaySymbols: Sets the standalone weekday symbols for the receiver. - (void)setStandaloneWeekdaySymbols:(NSArray *)array Parameters array An array of NSString objects that specify the standalone weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – standaloneWeekdaySymbols (page 418) – setWeekdaySymbols: (page 413) – setShortWeekdaySymbols: (page 407) – setVeryShortWeekdaySymbols: (page 413) – setShortStandaloneWeekdaySymbols: (page 407) – setVeryShortStandaloneWeekdaySymbols: (page 412) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 409setTimeStyle: Sets the time style of the receiver. - (void)setTimeStyle:(NSDateFormatterStyle)style Parameters style The time style for the receiver. For possible values, see NSDateFormatterStyle (page 424). Availability Available in iOS 2.0 and later. See Also – timeStyle (page 419) Related Sample Code DateSectionTitles Locations PhotoLocations URLCache XMLPerformance Declared in NSDateFormatter.h setTimeZone: Sets the time zone for the receiver. - (void)setTimeZone:(NSTimeZone *)tz Parameters tz The time zone for the receiver. Availability Available in iOS 2.0 and later. See Also – timeZone (page 420) Related Sample Code TableViewSuite NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 410Declared in NSDateFormatter.h setTwoDigitStartDate: Sets the two-digit start date for the receiver. - (void)setTwoDigitStartDate:(NSDate *)date Parameters date The earliest date that can be denoted by a two-digit year specifier. Availability Available in iOS 2.0 and later. See Also – twoDigitStartDate (page 420) Declared in NSDateFormatter.h setVeryShortMonthSymbols: Sets the very short month symbols for the receiver. - (void)setVeryShortMonthSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the very short month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – veryShortMonthSymbols (page 421) – setMonthSymbols: (page 403) – setShortMonthSymbols: (page 405) – setStandaloneMonthSymbols: (page 408) – setShortStandaloneMonthSymbols: (page 406) – setVeryShortStandaloneMonthSymbols: (page 412) NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 411Declared in NSDateFormatter.h setVeryShortStandaloneMonthSymbols: Sets the very short standalone month symbols for the receiver. - (void)setVeryShortStandaloneMonthSymbols:(NSArray *)array Parameters array An array of NSString objects that specify the very short standalone month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – veryShortStandaloneMonthSymbols (page 421) – setMonthSymbols: (page 403) – setShortMonthSymbols: (page 405) – setVeryShortMonthSymbols: (page 411) – setStandaloneMonthSymbols: (page 408) – setShortStandaloneMonthSymbols: (page 406) Declared in NSDateFormatter.h setVeryShortStandaloneWeekdaySymbols: Sets the very short standalone weekday symbols for the receiver. - (void)setVeryShortStandaloneWeekdaySymbols:(NSArray *)array Parameters array An array of NSString objects that specify the very short standalone weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – veryShortStandaloneWeekdaySymbols (page 422) NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 412– setWeekdaySymbols: (page 413) – setShortWeekdaySymbols: (page 407) – setVeryShortWeekdaySymbols: (page 413) – setStandaloneWeekdaySymbols: (page 409) – setShortStandaloneWeekdaySymbols: (page 407) Declared in NSDateFormatter.h setVeryShortWeekdaySymbols: Sets the vert short weekday symbols for the receiver - (void)setVeryShortWeekdaySymbols:(NSArray *)array Parameters array An array of NSString objects that specify the very short weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – veryShortWeekdaySymbols (page 422) – setWeekdaySymbols: (page 413) – setShortWeekdaySymbols: (page 407) – setStandaloneWeekdaySymbols: (page 409) – setShortStandaloneWeekdaySymbols: (page 407) – setVeryShortStandaloneWeekdaySymbols: (page 412) Declared in NSDateFormatter.h setWeekdaySymbols: Sets the weekday symbols for the receiver. - (void)setWeekdaySymbols:(NSArray *)array Parameters array An array of NSString objects that specify the weekday symbols for the receiver. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 413Availability Available in iOS 2.0 and later. See Also – weekdaySymbols (page 423) – setShortWeekdaySymbols: (page 407) – setVeryShortWeekdaySymbols: (page 413) – setStandaloneWeekdaySymbols: (page 409) – setShortStandaloneWeekdaySymbols: (page 407) – setVeryShortStandaloneWeekdaySymbols: (page 412) Declared in NSDateFormatter.h shortMonthSymbols Returns the array of short month symbols for the receiver. - (NSArray *)shortMonthSymbols Return Value An array containing NSString objects representing the short month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortMonthSymbols: (page 405) – monthSymbols (page 394) – veryShortMonthSymbols (page 421) – standaloneMonthSymbols (page 417) – shortStandaloneMonthSymbols (page 415) – veryShortStandaloneMonthSymbols (page 421) Declared in NSDateFormatter.h shortQuarterSymbols Returns the short quarter symbols for the receiver. - (NSArray *)shortQuarterSymbols NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 414Return Value An array containing NSString objects representing the short quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortQuarterSymbols: (page 405) – quarterSymbols (page 395) – standaloneQuarterSymbols (page 418) – shortStandaloneQuarterSymbols (page 415) Declared in NSDateFormatter.h shortStandaloneMonthSymbols Returns the short standalone month symbols for the receiver. - (NSArray *)shortStandaloneMonthSymbols Return Value An array of NSString objects that specify the short standalone month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortStandaloneMonthSymbols: (page 406) – monthSymbols (page 394) – shortMonthSymbols (page 414) – veryShortMonthSymbols (page 421) – standaloneMonthSymbols (page 417) – veryShortStandaloneMonthSymbols (page 421) Declared in NSDateFormatter.h shortStandaloneQuarterSymbols Returns the short standalone quarter symbols for the receiver. - (NSArray *)shortStandaloneQuarterSymbols NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 415Return Value An array containing NSString objects representing the short standalone quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortStandaloneQuarterSymbols: (page 406) – quarterSymbols (page 395) – shortQuarterSymbols (page 414) – standaloneQuarterSymbols (page 418) Declared in NSDateFormatter.h shortStandaloneWeekdaySymbols Returns the array of short standalone weekday symbols for the receiver. - (NSArray *)shortStandaloneWeekdaySymbols Return Value An array of NSString objects that specify the short standalone weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortStandaloneWeekdaySymbols: (page 407) – weekdaySymbols (page 423) – shortWeekdaySymbols (page 416) – veryShortWeekdaySymbols (page 422) – standaloneWeekdaySymbols (page 418) – veryShortStandaloneWeekdaySymbols (page 422) Declared in NSDateFormatter.h shortWeekdaySymbols Returns the array of short weekday symbols for the receiver. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 416- (NSArray *)shortWeekdaySymbols Return Value An array of NSString objects that specify the short weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortWeekdaySymbols: (page 407) – weekdaySymbols (page 423) – veryShortWeekdaySymbols (page 422) – standaloneWeekdaySymbols (page 418) – shortStandaloneWeekdaySymbols (page 416) – veryShortStandaloneWeekdaySymbols (page 422) Declared in NSDateFormatter.h standaloneMonthSymbols Returns the standalone month symbols for the receiver. - (NSArray *)standaloneMonthSymbols Return Value An array of NSString objects that specify the standalone month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – monthSymbols (page 394) – setStandaloneMonthSymbols: (page 408) – shortMonthSymbols (page 414) – veryShortMonthSymbols (page 421) – shortStandaloneMonthSymbols (page 415) – veryShortStandaloneMonthSymbols (page 421) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 417standaloneQuarterSymbols Returns the standalone quarter symbols for the receiver. - (NSArray *)standaloneQuarterSymbols Return Value An array containing NSString objects representing the standalone quarter symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setStandaloneQuarterSymbols: (page 408) – quarterSymbols (page 395) – shortQuarterSymbols (page 414) – shortStandaloneQuarterSymbols (page 415) Declared in NSDateFormatter.h standaloneWeekdaySymbols Returns the array of standalone weekday symbols for the receiver. - (NSArray *)standaloneWeekdaySymbols Return Value An array of NSString objects that specify the standalone weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setStandaloneWeekdaySymbols: (page 409) – weekdaySymbols (page 423) – shortWeekdaySymbols (page 416) – veryShortWeekdaySymbols (page 422) – shortStandaloneWeekdaySymbols (page 416) – veryShortStandaloneWeekdaySymbols (page 422) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 418stringFromDate: Returns a string representation of a given date formatted using the receiver’s current settings. - (NSString *)stringFromDate:(NSDate *)date Parameters date The date to format. Return Value A string representation of date formatted using the receiver’s current settings. Availability Available in iOS 2.0 and later. See Also – dateFromString: (page 388) + localizedStringFromDate:dateStyle:timeStyle: (page 386) Related Sample Code DateSectionTitles PhotoLocations SimpleFTPSample TableViewSuite Declared in NSDateFormatter.h timeStyle Returns the time style of the receiver. - (NSDateFormatterStyle)timeStyle Return Value The time style of the receiver. For possible values, see NSDateFormatterStyle (page 424). Availability Available in iOS 2.0 and later. See Also – setTimeStyle: (page 410) NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 419Related Sample Code SimpleFTPSample Declared in NSDateFormatter.h timeZone Returns the time zone for the receiver. - (NSTimeZone *)timeZone Return Value The time zone for the receiver. Availability Available in iOS 2.0 and later. See Also – setTimeZone: (page 410) Declared in NSDateFormatter.h twoDigitStartDate Returns the earliest date that can be denoted by a two-digit year specifier. - (NSDate *)twoDigitStartDate Return Value The earliest date that can be denoted by a two-digit year specifier. Discussion If the two-digit start date is set to January 6, 1976, then “January 1, 76” is interpreted as New Year's Day in 2076, whereas “February 14, 76” is interpreted as Valentine's Day in 1976. The default date is December 31, 1949. Availability Available in iOS 2.0 and later. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 420See Also – setTwoDigitStartDate: (page 411) Declared in NSDateFormatter.h veryShortMonthSymbols Returns the very short month symbols for the receiver. - (NSArray *)veryShortMonthSymbols Return Value An array of NSString objects that specify the very short month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setVeryShortMonthSymbols: (page 411) – monthSymbols (page 394) – shortMonthSymbols (page 414) – standaloneMonthSymbols (page 417) – shortStandaloneMonthSymbols (page 415) – veryShortStandaloneMonthSymbols (page 421) Declared in NSDateFormatter.h veryShortStandaloneMonthSymbols Returns the very short month symbols for the receiver. - (NSArray *)veryShortStandaloneMonthSymbols Return Value An array of NSString objects that specify the very short standalone month symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setVeryShortStandaloneMonthSymbols: (page 412) NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 421– monthSymbols (page 394) – shortMonthSymbols (page 414) – veryShortMonthSymbols (page 421) – standaloneMonthSymbols (page 417) – shortStandaloneMonthSymbols (page 415) Declared in NSDateFormatter.h veryShortStandaloneWeekdaySymbols Returns the array of very short standalone weekday symbols for the receiver. - (NSArray *)veryShortStandaloneWeekdaySymbols Return Value An array of NSString objects that specify the very short standalone weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setShortStandaloneWeekdaySymbols: (page 407) – weekdaySymbols (page 423) – shortWeekdaySymbols (page 416) – veryShortWeekdaySymbols (page 422) – standaloneWeekdaySymbols (page 418) – shortStandaloneWeekdaySymbols (page 416) Declared in NSDateFormatter.h veryShortWeekdaySymbols Returns the array of very short weekday symbols for the receiver. - (NSArray *)veryShortWeekdaySymbols Return Value An array of NSString objects that specify the very short weekday symbols for the receiver. NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 422Availability Available in iOS 2.0 and later. See Also – setVeryShortWeekdaySymbols: (page 413) – weekdaySymbols (page 423) – shortWeekdaySymbols (page 416) – standaloneWeekdaySymbols (page 418) – shortStandaloneWeekdaySymbols (page 416) – veryShortStandaloneWeekdaySymbols (page 422) Declared in NSDateFormatter.h weekdaySymbols Returns the array of weekday symbols for the receiver. - (NSArray *)weekdaySymbols Return Value An array of NSString objects that specify the weekday symbols for the receiver. Availability Available in iOS 2.0 and later. See Also – setWeekdaySymbols: (page 413) – shortWeekdaySymbols (page 416) – veryShortWeekdaySymbols (page 422) – standaloneWeekdaySymbols (page 418) – shortStandaloneWeekdaySymbols (page 416) – veryShortStandaloneWeekdaySymbols (page 422) Declared in NSDateFormatter.h NSDateFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 423Constants NSDateFormatterStyle The following constants specify predefined format styles for dates and times. typedef enum { NSDateFormatterNoStyle = kCFDateFormatterNoStyle, NSDateFormatterShortStyle = kCFDateFormatterShortStyle, NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle, NSDateFormatterLongStyle = kCFDateFormatterLongStyle, NSDateFormatterFullStyle = kCFDateFormatterFullStyle } NSDateFormatterStyle; Constants NSDateFormatterNoStyle Specifies no style. Equal to kCFDateFormatterNoStyle. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. NSDateFormatterShortStyle Specifies a short style, typically numeric only, such as “11/23/37” or “3:30pm”. Equal to kCFDateFormatterShortStyle. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. NSDateFormatterMediumStyle Specifies a medium style, typically with abbreviated text, such as “Nov 23, 1937”. Equal to kCFDateFormatterMediumStyle. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. NSDateFormatterLongStyle Specifies a long style, typically with full text, such as “November 23, 1937” or “3:30:32pm”. Equal to kCFDateFormatterLongStyle. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. NSDateFormatter Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 424NSDateFormatterFullStyle Specifies a full style with complete details, such as “Tuesday, April 12, 1952 AD” or “3:30:42pm PST”. Equal to kCFDateFormatterFullStyle. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. Discussion The format for these date and time styles is not exact because they depend on the locale, user preference settings, and the operating system version. Do not use these constants if you want an exact format. Availability Available in iOS 2.0 and later. Declared in NSDateFormatter.h NSDateFormatterBehavior Constants that specify the behavior NSDateFormatter should exhibit. typedef enum { NSDateFormatterBehaviorDefault = 0, NSDateFormatterBehavior10_0 = 1000, NSDateFormatterBehavior10_4 = 1040, } NSDateFormatterBehavior; Constants NSDateFormatterBehaviorDefault Specifies default formatting behavior. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. NSDateFormatterBehavior10_0 Specifies formatting behavior equivalent to that in Mac OS X 10.0. Available in iOS 2.0 through iOS 2.1. Declared in NSDateFormatter.h. NSDateFormatterBehavior10_4 Specifies formatting behavior equivalent for Mac OS X 10.4. Available in iOS 2.0 and later. Declared in NSDateFormatter.h. NSDateFormatter Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 425Availability Available in iOS 2.0 and later. Declared in NSDateFormatter.h NSDateFormatter Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 426Inherits from NSNumber : NSValue : NSObject Conforms to NSCoding (NSValue) NSCopying (NSValue) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSDecimalNumber.h Companion guide Number and Value Programming Topics Related sample code iPhoneCoreDataRecipes Overview NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127. Tasks Creating a Decimal Number + decimalNumberWithDecimal: (page 431) Creates and returns an NSDecimalNumber object equivalent to a given NSDecimal structure. + decimalNumberWithMantissa:exponent:isNegative: (page 431) Creates and returns an NSDecimalNumber object equivalent to the number specified by the arguments. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 427 NSDecimalNumber Class Reference+ decimalNumberWithString: (page 432) Creates and returns an NSDecimalNumber object whose value is equivalent to that in a given numeric string. + decimalNumberWithString:locale: (page 433) Creates and returns an NSDecimalNumber object whose value is equivalent to that in a given numeric string, interpreted using a given locale. + one (page 436) Returns an NSDecimalNumber object equivalent to the number 1.0. + zero (page 437) Returns an NSDecimalNumber object equivalent to the number 0.0. + notANumber (page 435) Returns an NSDecimalNumber object that specifies no number. Initializing a Decimal Number – initWithDecimal: (page 445) Returns an NSDecimalNumber object initialized to represent a given decimal. – initWithMantissa:exponent:isNegative: (page 446) Returns an NSDecimalNumber object initialized using the given mantissa, exponent, and sign. – initWithString: (page 446) Returns an NSDecimalNumber object initialized so that its value is equivalent to that in a given numeric string. – initWithString:locale: (page 447) Returns an NSDecimalNumber object initialized so that its value is equivalent to that in a given numeric string, interpreted using a given locale. Performing Arithmetic – decimalNumberByAdding: (page 438) Returns a new NSDecimalNumber object whose value is the sum of the receiver and another given NSDecimalNumber object. – decimalNumberBySubtracting: (page 443) Returns a new NSDecimalNumber object whose value is that of another given NSDecimalNumber object subtracted from the value of the receiver. NSDecimalNumber Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 428– decimalNumberByMultiplyingBy: (page 440) Returns a new NSDecimalNumber object whose value is the value of the receiver multiplied by that of another given NSDecimalNumber object. – decimalNumberByDividingBy: (page 439) Returns a new NSDecimalNumber object whose value is the value of the receiver divided by that of another given NSDecimalNumber object. – decimalNumberByRaisingToPower: (page 441) Returns a new NSDecimalNumber object whose value is the value of the receiver raised to a given power. – decimalNumberByMultiplyingByPowerOf10: (page 441) Multiplies the receiver by 10^power and returns the product, a newly created NSDecimalNumber object. – decimalNumberByAdding:withBehavior: (page 438) Adds decimalNumber to the receiver and returns the sum, a newly created NSDecimalNumber object. – decimalNumberBySubtracting:withBehavior: (page 444) Subtracts decimalNumber from the receiver and returns the difference, a newly created NSDecimalNumber object. – decimalNumberByMultiplyingBy:withBehavior: (page 440) Multiplies the receiver by decimalNumber and returns the product, a newly created NSDecimalNumber object. – decimalNumberByDividingBy:withBehavior: (page 439) Divides the receiver by decimalNumber and returns the quotient, a newly created NSDecimalNumber object. – decimalNumberByRaisingToPower:withBehavior: (page 442) Raises the receiver to power and returns the result, a newly created NSDecimalNumber object. – decimalNumberByMultiplyingByPowerOf10:withBehavior: (page 441) Multiplies the receiver by 10^power and returns the product, a newly created NSDecimalNumber object. Rounding Off – decimalNumberByRoundingAccordingToBehavior: (page 442) Rounds the receiver off in the way specified by behavior and returns the result, a newly created NSDecimalNumber object. NSDecimalNumber Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 429Accessing the Value – decimalValue (page 444) Returns the receiver’s value, expressed as an NSDecimal structure. – doubleValue (page 445) Returns the approximate value of the receiver as a double. – descriptionWithLocale: (page 444) Returns a string, specified according to a given locale, that represents the contents of the receiver. – objCType (page 448) Returns a C string containing the Objective-C type of the data contained in the receiver, which for an NSDecimalNumber object is always “d” (for double). Managing Behavior + defaultBehavior (page 434) Returns the way arithmetic methods, like decimalNumberByAdding: (page 438), round off and handle error conditions. + setDefaultBehavior: (page 436) Specifies the way that arithmetic methods, like decimalNumberByAdding: (page 438), round off and handle error conditions. Comparing Decimal Numbers – compare: (page 437) Returns an NSComparisonResult value that indicates the numerical ordering of the receiver and another given NSDecimalNumber object. Getting Maximum and Minimum Possible Values + maximumDecimalNumber (page 434) Returns the largest possible value of an NSDecimalNumber object. + minimumDecimalNumber (page 435) Returns the smallest possible value of an NSDecimalNumber object. NSDecimalNumber Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 430Class Methods decimalNumberWithDecimal: Creates and returns an NSDecimalNumber object equivalent to a given NSDecimal structure. + (NSDecimalNumber *)decimalNumberWithDecimal:(NSDecimal)decimal Parameters decimal An NSDecimal structure that specifies the value for the new decimal number object. Return Value An NSDecimalNumber object equivalent to decimal. Discussion You can initialize decimal programmatically or generate it using the NSScanner method, scanDecimal: (page 1449) Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h decimalNumberWithMantissa:exponent:isNegative: Creates and returns an NSDecimalNumber object equivalent to the number specified by the arguments. + (NSDecimalNumber *)decimalNumberWithMantissa:(unsigned long long)mantissa exponent:(short)exponent isNegative:(BOOL)isNegative Parameters mantissa The mantissa for the new decimal number object. exponent The exponent for the new decimal number object. isNegative A Boolean value that specifies whether the sign of the number is negative. NSDecimalNumber Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 431Discussion The arguments express a number in a kind of scientific notation that requires the mantissa to be an integer. So, for example, if the number to be represented is –12.345, it is expressed as 12345x10^–3—mantissa is 12345; exponent is –3; and isNegative is YES, as illustrated by the following example. NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithMantissa:12345 exponent:-3 isNegative:YES]; Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h decimalNumberWithString: Creates and returns an NSDecimalNumber object whose value is equivalent to that in a given numeric string. + (NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString Parameters numericString A numeric string. Besides digits, numericString can include an initial “+” or “–”; a single “E” or “e”, to indicate the exponent of a number in scientific notation; and a single NSDecimalSeparator to divide the fractional from the integral part of the number. Return Value An NSDecimalNumber object whose value is equivalent to numericString. Discussion Whether the NSDecimalSeparator is a period (as is used, for example, in the United States) or a comma (as is used, for example, in France) depends on the default locale. Availability Available in iOS 2.0 and later. See Also + decimalNumberWithString:locale: (page 433) NSDecimalNumber Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 432Declared in NSDecimalNumber.h decimalNumberWithString:locale: Creates and returns an NSDecimalNumber object whose value is equivalent to that in a given numeric string, interpreted using a given locale. + (NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString locale:(NSDictionary *)locale Parameters numericString A numeric string. Besides digits, numericString can include an initial “+” or “–”; a single “E” or “e”, to indicate the exponent of a number in scientific notation; and a single NSDecimalSeparator to divide the fractional from the integral part of the number. locale A dictionary that defines the locale (specifically the NSDecimalSeparator) to use to interpret the number in numericString. Return Value An NSDecimalNumber object whose value is equivalent to numericString. Discussion The locale parameter determines whether the NSDecimalSeparator is a period (as is used, for example, in the United States) or a comma (as is used, for example, in France). The following strings show examples of acceptable values for numericString: “2500.6” (or “2500,6”, depending on locale) “–2500.6” (or “–2500.6”) “–2.5006e3” (or “–2,5006e3”) “–2.5006E3” (or “–2,5006E3”) The following strings are unacceptable: “2,500.6” “2500 3/5” “2.5006x10e3” NSDecimalNumber Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 433“two thousand five hundred and six tenths” Availability Available in iOS 2.0 and later. See Also + decimalNumberWithString: (page 432) Declared in NSDecimalNumber.h defaultBehavior Returns the way arithmetic methods, like decimalNumberByAdding: (page 438), round off and handle error conditions. + (id < NSDecimalNumberBehaviors >)defaultBehavior Discussion By default, the arithmetic methods use the NSRoundPlain behavior; that is, the methods round to the closest possible return value. The methods assume your need for precision does not exceed 38 significant digits and raise exceptions when they try to divide by 0 or produce a number too big or too small to be represented. If this default behavior doesn’t suit your application, you should use methods that let you specify the behavior, like decimalNumberByAdding:withBehavior: (page 438). If you find yourself using a particular behavior consistently, you can specify a different default behavior with setDefaultBehavior: (page 436). Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h maximumDecimalNumber Returns the largest possible value of an NSDecimalNumber object. + (NSDecimalNumber *)maximumDecimalNumber Return Value The largest possible value of an NSDecimalNumber object. NSDecimalNumber Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 434Availability Available in iOS 2.0 and later. See Also + minimumDecimalNumber (page 435) Declared in NSDecimalNumber.h minimumDecimalNumber Returns the smallest possible value of an NSDecimalNumber object. + (NSDecimalNumber *)minimumDecimalNumber Return Value The smallest possible value of an NSDecimalNumber object. Availability Available in iOS 2.0 and later. See Also + maximumDecimalNumber (page 434) Declared in NSDecimalNumber.h notANumber Returns an NSDecimalNumber object that specifies no number. + (NSDecimalNumber *)notANumber Return Value An NSDecimalNumber object that specifies no number. Discussion Any arithmetic method receiving notANumber as an argument returns notANumber. This value can be a useful way of handling non-numeric data in an input file. This method can also be a useful response to calculation errors. For more information on calculation errors, see the exceptionDuringOperation:error:leftOperand:rightOperand: (page 2004) method description in the NSDecimalNumberBehaviors protocol specification. NSDecimalNumber Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 435Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h one Returns an NSDecimalNumber object equivalent to the number 1.0. + (NSDecimalNumber *)one Return Value An NSDecimalNumber object equivalent to the number 1.0. Availability Available in iOS 2.0 and later. See Also + zero (page 437) Declared in NSDecimalNumber.h setDefaultBehavior: Specifies the way that arithmetic methods, like decimalNumberByAdding: (page 438), round off and handle error conditions. + (void)setDefaultBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior must conform to the NSDecimalNumberBehaviors protocol. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 436zero Returns an NSDecimalNumber object equivalent to the number 0.0. + (NSDecimalNumber *)zero Return Value An NSDecimalNumber object equivalent to the number 0.0. Availability Available in iOS 2.0 and later. See Also + one (page 436) Declared in NSDecimalNumber.h Instance Methods compare: Returns an NSComparisonResult value that indicates the numerical ordering of the receiver and another given NSDecimalNumber object. - (NSComparisonResult)compare:(NSNumber *)decimalNumber Parameters decimalNumber The number with which to compare the receiver. This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of Mac OS X. Return Value NSOrderedAscending if the value of decimalNumber is greater than the receiver; NSOrderedSame if they’re equal; and NSOrderedDescending if the value of decimalNumber is less than the receiver. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 437decimalNumberByAdding: Returns a new NSDecimalNumber object whose value is the sum of the receiver and another given NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber Parameters decimalNumber The number to add to the receiver. Return Value A new NSDecimalNumber object whose value is the sum of the receiver and decimalNumber. Discussion This method uses the default behavior when handling calculation errors and rounding. Availability Available in iOS 2.0 and later. See Also – decimalNumberByAdding:withBehavior: (page 438) + defaultBehavior (page 434) Declared in NSDecimalNumber.h decimalNumberByAdding:withBehavior: Adds decimalNumber to the receiver and returns the sum, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber withBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior specifies the handling of calculation errors and rounding. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 438decimalNumberByDividingBy: Returns a new NSDecimalNumber object whose value is the value of the receiver divided by that of another given NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber Parameters decimalNumber The number by which to divide the receiver. Return Value A new NSDecimalNumber object whose value is the value of the receiver divided by decimalNumber. Discussion This method uses the default behavior when handling calculation errors and rounding. Availability Available in iOS 2.0 and later. See Also – decimalNumberByDividingBy:withBehavior: (page 439) + defaultBehavior (page 434) Declared in NSDecimalNumber.h decimalNumberByDividingBy:withBehavior: Divides the receiver by decimalNumber and returns the quotient, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber withBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior specifies the handling of calculation errors and rounding. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 439decimalNumberByMultiplyingBy: Returns a new NSDecimalNumber object whose value is the value of the receiver multiplied by that of another given NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber Parameters decimalNumber The number by which to multiply the receiver. Return Value A new NSDecimalNumber object whose value is decimalNumber multiplied by the receiver. Discussion This method uses the default behavior when handling calculation errors and when rounding. Availability Available in iOS 2.0 and later. See Also – decimalNumberByMultiplyingBy:withBehavior: (page 440) + defaultBehavior (page 434) Declared in NSDecimalNumber.h decimalNumberByMultiplyingBy:withBehavior: Multiplies the receiver by decimalNumber and returns the product, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber withBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior specifies the handling of calculation errors and rounding. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 440decimalNumberByMultiplyingByPowerOf10: Multiplies the receiver by 10^power and returns the product, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power Discussion This method uses the default behavior when handling calculation errors and when rounding. Availability Available in iOS 2.0 and later. See Also – decimalNumberByMultiplyingByPowerOf10:withBehavior: (page 441) + defaultBehavior (page 434) Declared in NSDecimalNumber.h decimalNumberByMultiplyingByPowerOf10:withBehavior: Multiplies the receiver by 10^power and returns the product, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByMultiplyingByPowerOf10:(short)power withBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior specifies the handling of calculation errors and rounding. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h decimalNumberByRaisingToPower: Returns a new NSDecimalNumber object whose value is the value of the receiver raised to a given power. - (NSDecimalNumber *)decimalNumberByRaisingToPower:(NSUInteger)power Parameters power The power to which to raise the receiver. NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 441Return Value A new NSDecimalNumber object whose value is the value of the receiver raised to the power power. Discussion This method uses the default behavior when handling calculation errors and when rounding. Availability Available in iOS 2.0 and later. See Also – decimalNumberByRaisingToPower:withBehavior: (page 442) + defaultBehavior (page 434) Declared in NSDecimalNumber.h decimalNumberByRaisingToPower:withBehavior: Raises the receiver to power and returns the result, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByRaisingToPower:(NSUInteger)power withBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior specifies the handling of calculation errors and rounding. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h decimalNumberByRoundingAccordingToBehavior: Rounds the receiver off in the way specified by behavior and returns the result, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberByRoundingAccordingToBehavior:(id < NSDecimalNumberBehaviors >)behavior NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 442Discussion For a description of the different ways of rounding, see the roundingMode (page 1159) method in the NSDecimalNumberBehaviors protocol specification. Availability Available in iOS 2.0 and later. Related Sample Code iPhoneCoreDataRecipes Declared in NSDecimalNumber.h decimalNumberBySubtracting: Returns a new NSDecimalNumber object whose value is that of another given NSDecimalNumber object subtracted from the value of the receiver. - (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber Parameters decimalNumber The number to subtract from the receiver. Return Value A new NSDecimalNumber object whose value is decimalNumber subtracted from the receiver. Discussion This method uses the default behavior when handling calculation errors and when rounding. Availability Available in iOS 2.0 and later. See Also – decimalNumberBySubtracting:withBehavior: (page 444) + defaultBehavior (page 434) Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 443decimalNumberBySubtracting:withBehavior: Subtracts decimalNumber from the receiver and returns the difference, a newly created NSDecimalNumber object. - (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber withBehavior:(id < NSDecimalNumberBehaviors >)behavior Discussion behavior specifies the handling of calculation errors and rounding. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h decimalValue Returns the receiver’s value, expressed as an NSDecimal structure. - (NSDecimal)decimalValue Return Value The receiver’s value, expressed as an NSDecimal structure. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h descriptionWithLocale: Returns a string, specified according to a given locale, that represents the contents of the receiver. - (NSString *)descriptionWithLocale:(NSDictionary *)locale Parameters locale A dictionary that defines the locale (specifically the NSDecimalSeparator) to use to generate the returned string. NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 444Return Value A string that represents the contents of the receiver, according to locale. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h doubleValue Returns the approximate value of the receiver as a double. - (double)doubleValue Return Value The approximate value of the receiver as a double. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h initWithDecimal: Returns an NSDecimalNumber object initialized to represent a given decimal. - (id)initWithDecimal:(NSDecimal)decimal Parameters decimal The value of the new object. Return Value An NSDecimalNumber object initialized to represent decimal. Discussion This method is the designated initializer for NSDecimalNumber. Availability Available in iOS 2.0 and later. NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 445Declared in NSDecimalNumber.h initWithMantissa:exponent:isNegative: Returns an NSDecimalNumber object initialized using the given mantissa, exponent, and sign. - (id)initWithMantissa:(unsigned long long)mantissa exponent:(short)exponent isNegative:(BOOL)flag Parameters mantissa The mantissa for the new decimal number object. exponent The exponent for the new decimal number object. flag A Boolean value that specifies whether the sign of the number is negative. Return Value An NSDecimalNumber object initialized using the given mantissa, exponent, and sign. Discussion The arguments express a number in a type of scientific notation that requires the mantissa to be an integer. So, for example, if the number to be represented is 1.23, it is expressed as 123x10^–2—mantissa is 123; exponent is –2; and isNegative, which refers to the sign of the mantissa, is NO. Availability Available in iOS 2.0 and later. See Also + decimalNumberWithMantissa:exponent:isNegative: (page 431) Declared in NSDecimalNumber.h initWithString: Returns an NSDecimalNumber object initialized so that its value is equivalent to that in a given numeric string. - (id)initWithString:(NSString *)numericString NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 446Parameters numericString A numeric string. Besides digits, numericString can include an initial “+” or “–”; a single “E” or “e”, to indicate the exponent of a number in scientific notation; and a single NSDecimalSeparator to divide the fractional from the integral part of the number. For a listing of acceptable and unacceptable strings, see the class method decimalNumberWithString:locale: (page 433). Return Value An NSDecimalNumber object initialized so that its value is equivalent to that in numericString. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h initWithString:locale: Returns an NSDecimalNumber object initialized so that its value is equivalent to that in a given numeric string, interpreted using a given locale. - (id)initWithString:(NSString *)numericString locale:(NSDictionary *)locale Parameters numericString A numeric string. Besides digits, numericString can include an initial “+” or “–”; a single “E” or “e”, to indicate the exponent of a number in scientific notation; and a single NSDecimalSeparator to divide the fractional from the integral part of the number. locale A dictionary that defines the locale (specifically the NSDecimalSeparator) to use to interpret the number in numericString. Return Value An NSDecimalNumber object initialized so that its value is equivalent to that in numericString, interpreted using locale. Availability Available in iOS 2.0 and later. NSDecimalNumber Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 447See Also + decimalNumberWithString:locale: (page 433) Declared in NSDecimalNumber.h objCType Returns a C string containing the Objective-C type of the data contained in the receiver, which for an NSDecimalNumber object is always “d” (for double). - (const char *)objCType Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h Constants NSDecimalNumber Exception Names Names of the various exceptions raised by NSDecimalNumber to indicate computational errors. extern NSString *NSDecimalNumberExactnessException; extern NSString *NSDecimalNumberOverflowException; extern NSString *NSDecimalNumberUnderflowException; extern NSString *NSDecimalNumberDivideByZeroException; Constants NSDecimalNumberExactnessException The name of the exception raised if there is an exactness error. Available in iOS 2.0 and later. Declared in NSDecimalNumber.h. NSDecimalNumberOverflowException The name of the exception raised on overflow. Available in iOS 2.0 and later. Declared in NSDecimalNumber.h. NSDecimalNumber Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 448NSDecimalNumberUnderflowException The name of the exception raised on underflow. Available in iOS 2.0 and later. Declared in NSDecimalNumber.h. NSDecimalNumberDivideByZeroException The name of the exception raised on divide by zero. Available in iOS 2.0 and later. Declared in NSDecimalNumber.h. Declared in NSDecimalNumber.h NSDecimalNumber Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 449Inherits from NSObject Conforms to NSCoding NSDecimalNumberBehaviors NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSDecimalNumber.h Companion guide Number and Value Programming Topics Related sample code iPhoneCoreDataRecipes Overview NSDecimalNumberHandler is a class that adopts the NSDecimalNumberBehaviors protocol. This class allows you to set the way an NSDecimalNumber object rounds off and handles errors, without having to create a custom class. You can use an instance of this class as an argument to any of the NSDecimalNumber methods that end with ...Behavior:. If you don’t think you need special behavior, you probably don’t need this class—it is likely that NSDecimalNumber's default behavior will suit your needs. For more information, see the NSDecimalNumberBehaviors protocol specification. Adopted Protocols NSDecimalNumberBehaviors – roundingMode (page 2005) – scale (page 2005) 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 450 NSDecimalNumberHandler Class Reference– exceptionDuringOperation:error:leftOperand:rightOperand: (page 2004) NSCoding – encodeWithCoder: (page 1999) – initWithCoder: (page 1999) Tasks Creating a Decimal Number Handler + defaultDecimalNumberHandler (page 452) Returns the default instance of NSDecimalNumberHandler. + decimalNumberHandlerWithRoundingMode:scale:raiseOnExactness:raiseOnOverflow:raiseOnUnderflow:raiseOnDivideByZero: (page 451) Returns an NSDecimalNumberHandler object with customized behavior. Initializing a Decimal Number Handler – initWithRoundingMode:scale:raiseOnExactness:raiseOnOverflow:raiseOnUnderflow:raiseOnDivideByZero: (page 453) Returns an NSDecimalNumberHandler object initialized so it behaves as specified by the method’s arguments. Class Methods decimalNumberHandlerWithRoundingMode:scale:raiseOnExactness:raiseOnOverflow: raiseOnUnderflow:raiseOnDivideByZero: Returns an NSDecimalNumberHandler object with customized behavior. + (id)decimalNumberHandlerWithRoundingMode:(NSRoundingMode)roundingMode scale:(short)scale raiseOnExactness:(BOOL)raiseOnExactness raiseOnOverflow:(BOOL)raiseOnOverflow raiseOnUnderflow:(BOOL)raiseOnUnderflow raiseOnDivideByZero:(BOOL)raiseOnDivideByZero NSDecimalNumberHandler Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 451Parameters roundingMode The rounding mode to use. There are four possible values: NSRoundUp, NSRoundDown, NSRoundPlain, and NSRoundBankers. scale The number of digits a rounded value should have after its decimal point. raiseOnExactness If YES, in the event of an exactness error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method. raiseOnOverflow If YES, in the event of an overflow error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method raiseOnUnderflow If YES, in the event of an underflow error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method raiseOnDivideByZero If YES, in the event of a divide by zero error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method Return Value An NSDecimalNumberHandler object with customized behavior. Discussion See the NSDecimalNumberBehaviors protocol specification for a complete explanation of the possible behaviors. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h defaultDecimalNumberHandler Returns the default instance of NSDecimalNumberHandler. + (id)defaultDecimalNumberHandler Return Value The default instance of NSDecimalNumberHandler. NSDecimalNumberHandler Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 452Discussion This default decimal number handler rounds to the closest possible return value. It assumes your need for precision does not exceed 38 significant digits, and it raises an exception when its NSDecimalNumber object tries to divide by 0 or when its NSDecimalNumber object produces a number too big or too small to be represented. Availability Available in iOS 2.0 and later. Declared in NSDecimalNumber.h Instance Methods initWithRoundingMode:scale:raiseOnExactness:raiseOnOverflow:raiseOnUnderflow: raiseOnDivideByZero: Returns an NSDecimalNumberHandler object initialized so it behaves as specified by the method’s arguments. - (id)initWithRoundingMode:(NSRoundingMode)roundingMode scale:(short)scale raiseOnExactness:(BOOL)raiseOnExactness raiseOnOverflow:(BOOL)raiseOnOverflow raiseOnUnderflow:(BOOL)raiseOnUnderflow raiseOnDivideByZero:(BOOL)raiseOnDivideByZero Parameters roundingMode The rounding mode to use. There are four possible values: NSRoundUp, NSRoundDown, NSRoundPlain, and NSRoundBankers. scale The number of digits a rounded value should have after its decimal point. raiseOnExactness If YES, in the event of an exactness error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method. raiseOnOverflow If YES, in the event of an overflow error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method raiseOnUnderflow If YES, in the event of an underflow error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method NSDecimalNumberHandler Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 453raiseOnDivideByZero If YES, in the event of a divide by zero error the handler will raise an exception, otherwise it will ignore the error and return control to the calling method Return Value An initialized NSDecimalNumberHandler object initialized with customized behavior. The returned object might be different than the original receiver. Discussion See the NSDecimalNumberBehaviors protocol specification for a complete explanation of the possible behaviors. Availability Available in iOS 2.0 and later. Related Sample Code iPhoneCoreDataRecipes Declared in NSDecimalNumber.h NSDecimalNumberHandler Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 454Inherits from NSObject Conforms to NSCoding NSCopying NSMutableCopying NSFastEnumeration NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSDictionary.h Foundation/NSFileManager.h Foundation/NSKeyValueCoding.h Companion guides Collections Programming Topics Property List Programming Guide Related sample code DrillDownSave GenericKeychain International Mountains LocateMe SimpleFTPSample Overview The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. Use this class or its subclass NSMutableDictionary when you need a convenient and efficient way to retrieve data associated with an arbitrary key. NSDictionary creates static dictionaries, and NSMutableDictionary creates dynamic dictionaries. (For convenience, we use the term dictionary to refer to any instance of one of these classes without specifying its exact class membership.) 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 455 NSDictionary Class ReferenceA key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual: (page 2122)). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see “Key-Value Coding Fundamentals”). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull. NSDictionary is “toll-free bridged” with its Core Foundation counterpart, CFDictionaryRef. See “Toll-Free Bridging” for more information on toll-free bridging. Subclassing Notes There should typically be little need to subclass NSDictionary. If you do need to customize behavior, it is often better to consider composition rather than subclassing. Methods to Override If you do need to subclass NSDictionary, you need to take into account that is represented by a Class cluster—there are therefore several primitive methods upon which the methods are conceptually based: count (page 470) objectForKey: (page 494) keyEnumerator (page 489) In a subclass, you must override all these methods. NSDictionary’s other methods operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once. Alternatives to Subclassing Before making a custom class of NSDictionary, investigate NSMapTable and the corresponding Core Foundation type, CFDictionary Reference. Because NSDictionary and CFDictionary are “toll-free bridged,” you can substitute a CFDictionary object for a NSDictionary object in your code (with appropriate casting). Although they are corresponding types, CFDictionary and NSDictionary do not have identical interfaces or implementations, and you can sometimes do things with CFDictionary that you cannot easily do with NSDictionary. NSDictionary Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 456If the behavior you want to add supplements that of the existing class, you could write a category on NSDictionary. Keep in mind, however, that this category will be in effect for all instances of NSDictionary that you use, and this might have unintended consequences. Alternatively, you could use composition to achieve the desired behavior. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSMutableCopying mutableCopyWithZone: (page 2103) NSFastEnumeration countByEnumeratingWithState:objects:count: (page 2013) Tasks Creating a Dictionary + dictionary (page 462) Creates and returns an empty dictionary. + dictionaryWithContentsOfFile: (page 462) Creates and returns a dictionary using the keys and values found in a file specified by a given path. + dictionaryWithContentsOfURL: (page 463) Creates and returns a dictionary using the keys and values found in a resource specified by a given URL. + dictionaryWithDictionary: (page 464) Creates and returns a dictionary containing the keys and values from another given dictionary. + dictionaryWithObject:forKey: (page 464) Creates and returns a dictionary containing a given key and value. + dictionaryWithObjects:forKeys: (page 465) Creates and returns a dictionary containing entries constructed from the contents of an array of keys and an array of values. NSDictionary Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 457+ dictionaryWithObjects:forKeys:count: (page 466) Creates and returns a dictionary containing count objects from the objects array. + dictionaryWithObjectsAndKeys: (page 467) Creates and returns a dictionary containing entries constructed from the specified set of values and keys. Initializing an NSDictionary Instance – initWithContentsOfFile: (page 483) Initializes a newly allocated dictionary using the keys and values found in a file at a given path. – initWithContentsOfURL: (page 483) Initializes a newly allocated dictionary using the keys and values found at a given URL. – initWithDictionary: (page 484) Initializes a newly allocated dictionary by placing in it the keys and values contained in another given dictionary. – initWithDictionary:copyItems: (page 485) Initializes a newly allocated dictionary using the objects contained in another given dictionary. – initWithObjects:forKeys: (page 486) Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays. – initWithObjects:forKeys:count: (page 486) Initializes a newly allocated dictionary with count entries. – initWithObjectsAndKeys: (page 487) Initializes a newly allocated dictionary with entries constructed from the specified set of values and keys. Counting Entries – count (page 470) Returns the number of entries in the dictionary. Comparing Dictionaries – isEqualToDictionary: (page 488) Returns a Boolean value that indicates whether the contents of the receiving dictionary are equal to the contents of another given dictionary. NSDictionary Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 458Accessing Keys and Values – allKeys (page 468) Returns a new array containing the dictionary’s keys. – allKeysForObject: (page 469) Returns a new array containing the keys corresponding to all occurrences of a given object in the dictionary. – allValues (page 470) Returns a new array containing the dictionary’s values. – getObjects:andKeys: (page 482) Returns by reference C arrays of the keys and values in the dictionary. – objectForKey: (page 494) Returns the value associated with a given key. – objectsForKeys:notFoundMarker: (page 495) Returns the set of objects from the dictionary that corresponds to the specified keys as an NSArray. – valueForKey: (page 495) Returns the value associated with a given key. Enumerating Dictionaries – keyEnumerator (page 489) Returns an enumerator object that lets you access each key in the dictionary. – objectEnumerator (page 493) Returns an enumerator object that lets you access each value in the dictionary. – enumerateKeysAndObjectsUsingBlock: (page 473) Applies a given block object to the entries of the dictionary. – enumerateKeysAndObjectsWithOptions:usingBlock: (page 474) Applies a given block object to the entries of the dictionary. Sorting Dictionaries – keysSortedByValueUsingSelector: (page 491) Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values. NSDictionary Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 459– keysSortedByValueUsingComparator: (page 491) Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block. – keysSortedByValueWithOptions:usingComparator: (page 492) Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block and a specified set of options. Filtering Dictionaries – keysOfEntriesPassingTest: (page 490) Returns the set of keys whose corresponding value satisfies a constraint described by a block object. – keysOfEntriesWithOptions:passingTest: (page 490) Returns the set of keys whose corresponding value satisfies a constraint described by a block object. Storing Dictionaries – writeToFile:atomically: (page 496) Writes a property list representation of the contents of the dictionary to a given path. – writeToURL:atomically: (page 497) Writes a property list representation of the contents of the dictionary to a given URL. Accessing File Attributes – fileCreationDate (page 474) Returns the value for the NSFileCreationDate key. – fileExtensionHidden (page 475) Returns the value for the NSFileExtensionHidden key. – fileGroupOwnerAccountID (page 475) Returns the value for the NSFileGroupOwnerAccountID key. – fileGroupOwnerAccountName (page 476) Returns the value for the NSFileGroupOwnerAccountName key. – fileHFSCreatorCode (page 476) Returns the value for the NSFileHFSCreatorCode key. NSDictionary Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 460– fileHFSTypeCode (page 477) Returns the value for the NSFileHFSTypeCode key. – fileIsAppendOnly (page 477) Returns the value for the NSFileAppendOnly key. – fileIsImmutable (page 477) Returns the value for the NSFileImmutable key. – fileModificationDate (page 478) Returns the value for the key NSFileModificationDate. – fileOwnerAccountID (page 478) Returns the value for the NSFileOwnerAccountID key. – fileOwnerAccountName (page 479) Returns the value for the key NSFileOwnerAccountName. – filePosixPermissions (page 479) Returns the value for the key NSFilePosixPermissions. – fileSize (page 480) Returns the value for the key NSFileSize. – fileSystemFileNumber (page 481) Returns the value for the key NSFileSystemFileNumber. – fileSystemNumber (page 481) Returns the value for the key NSFileSystemNumber. – fileType (page 482) Returns the value for the key NSFileType. Creating a Description – description (page 471) Returns a string that represents the contents of the dictionary, formatted as a property list. – descriptionInStringsFileFormat (page 471) Returns a string that represents the contents of the dictionary, formatted in .strings file format. – descriptionWithLocale: (page 472) Returns a string object that represents the contents of the dictionary, formatted as a property list. – descriptionWithLocale:indent: (page 472) Returns a string object that represents the contents of the dictionary, formatted as a property list. NSDictionary Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 461Class Methods dictionary Creates and returns an empty dictionary. + (id)dictionary Return Value A new empty dictionary. Discussion This method is declared primarily for use with mutable subclasses of NSDictionary. If you don’t want a temporary object, you can also create an empty dictionary using alloc... and init. Availability Available in iOS 2.0 and later. Related Sample Code LazyTableImages LocateMe TheElements Declared in NSDictionary.h dictionaryWithContentsOfFile: Creates and returns a dictionary using the keys and values found in a file specified by a given path. + (id)dictionaryWithContentsOfFile:(NSString *)path Parameters path A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary. Return Value A new dictionary that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary. NSDictionary Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 462Discussion The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable. Availability Available in iOS 2.0 and later. See Also – initWithContentsOfFile: (page 483) Related Sample Code AppPrefs DrillDownSave International Mountains SimpleFTPSample Declared in NSDictionary.h dictionaryWithContentsOfURL: Creates and returns a dictionary using the keys and values found in a resource specified by a given URL. + (id)dictionaryWithContentsOfURL:(NSURL *)aURL Parameters aURL An URL that identifies a resource containing a string representation of a property list whose root object is a dictionary. Return Value A new dictionary that contains the dictionary at aURL, or nil if there is an error or if the contents of the resource are an invalid representation of a dictionary. Discussion The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable. Availability Available in iOS 2.0 and later. NSDictionary Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 463See Also – initWithContentsOfURL: (page 483) Declared in NSDictionary.h dictionaryWithDictionary: Creates and returns a dictionary containing the keys and values from another given dictionary. + (id)dictionaryWithDictionary:(NSDictionary *)otherDictionary Parameters otherDictionary A dictionary containing the keys and values with which to initialize the new dictionary. Return Value A new dictionary containing the keys and values found in otherDictionary. Availability Available in iOS 2.0 and later. See Also – initWithDictionary: (page 484) Related Sample Code GenericKeychain Declared in NSDictionary.h dictionaryWithObject:forKey: Creates and returns a dictionary containing a given key and value. + (id)dictionaryWithObject:(id)anObject forKey:(id)aKey Parameters anObject The value corresponding to aKey. If this value is nil, an NSInvalidArgumentException is raised. NSDictionary Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 464aKey The key for anObject. If this value is nil, an NSInvalidArgumentException is raised. Return Value A new dictionary containing a single object, anObject, for a single key, aKey. Availability Available in iOS 2.0 and later. See Also + dictionaryWithObjects:forKeys: (page 465) + dictionaryWithObjects:forKeys:count: (page 466) + dictionaryWithObjectsAndKeys: (page 467) Related Sample Code BubbleLevel DrillDownSave LazyTableImages SeismicXML Declared in NSDictionary.h dictionaryWithObjects:forKeys: Creates and returns a dictionary containing entries constructed from the contents of an array of keys and an array of values. + (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys Parameters objects An array containing the values for the new dictionary. keys An array containing the keys for the new dictionary. Each key is copied (using copyWithZone: (page 2002); keys must conform to the NSCopying protocol), and the copy is added to the dictionary. Return Value A new dictionary containing entries constructed from the contents of objects and keys. NSDictionary Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 465Discussion This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if objects and keys don’t have the same number of elements. Availability Available in iOS 2.0 and later. See Also – initWithObjects:forKeys: (page 486) + dictionaryWithObject:forKey: (page 464) + dictionaryWithObjects:forKeys:count: (page 466) + dictionaryWithObjectsAndKeys: (page 467) Declared in NSDictionary.h dictionaryWithObjects:forKeys:count: Creates and returns a dictionary containing count objects from the objects array. + (id)dictionaryWithObjects:(id *)objects forKeys:(id *)keys count:(NSUInteger)count Parameters objects A C array of values for the new dictionary. keys A C array of keys for the new dictionary. Each key is copied (using copyWithZone: (page 2002); keys must conform to the NSCopying protocol), and the copy is added to the new dictionary. count The number of elements to use from the keys and objects arrays. count must not exceed the number of elements in objects or keys. Discussion This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if a key or value object is nil. The following code fragment illustrates how to create a dictionary that associates the alphabetic characters with their ASCII values: static const NSInteger N_ENTRIES = 26; NSDictionary Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 466NSDictionary *asciiDict; NSString *keyArray[N_ENTRIES]; NSNumber *valueArray[N_ENTRIES]; NSInteger i; for (i = 0; i < N_ENTRIES; i++) { char charValue = 'a' + i; keyArray[i] = [NSString stringWithFormat:@"%c", charValue]; valueArray[i] = [NSNumber numberWithChar:charValue]; } asciiDict = [NSDictionary dictionaryWithObjects:(id *)valueArray forKeys:(id *)keyArray count:N_ENTRIES]; Availability Available in iOS 2.0 and later. See Also – initWithObjects:forKeys:count: (page 486) + dictionaryWithObject:forKey: (page 464) + dictionaryWithObjects:forKeys: (page 465) + dictionaryWithObjectsAndKeys: (page 467) Declared in NSDictionary.h dictionaryWithObjectsAndKeys: Creates and returns a dictionary containing entries constructed from the specified set of values and keys. + (id)dictionaryWithObjectsAndKeys:(id)firstObject , ... Parameters firstObject The first value to add to the new dictionary. NSDictionary Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 467... First the key for firstObject, then a null-terminated list of alternating values and keys. If any key is nil, an NSInvalidArgumentException is raised. Discussion This method is similar to dictionaryWithObjects:forKeys: (page 465), differing only in the way key-value pairs are specified. For example: NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"value1", @"key1", @"value2", @"key2", nil]; Availability Available in iOS 2.0 and later. See Also – initWithObjectsAndKeys: (page 487) + dictionaryWithObject:forKey: (page 464) + dictionaryWithObjects:forKeys: (page 465) + dictionaryWithObjects:forKeys:count: (page 466) Related Sample Code International Mountains LocateMe PhotoLocations SpeakHere TouchCells Declared in NSDictionary.h Instance Methods allKeys Returns a new array containing the dictionary’s keys. - (NSArray *)allKeys NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 468Return Value A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries. Discussion The order of the elements in the array is not defined. Availability Available in iOS 2.0 and later. See Also – allValues (page 470) – allKeysForObject: (page 469) – getObjects:andKeys: (page 482) Declared in NSDictionary.h allKeysForObject: Returns a new array containing the keys corresponding to all occurrences of a given object in the dictionary. - (NSArray *)allKeysForObject:(id)anObject Parameters anObject The value to look for in the dictionary. Return Value A new array containing the keys corresponding to all occurrences of anObject in the dictionary. If no object matching anObject is found, returns an empty array. Discussion Each object in the dictionary is sent an isEqual: (page 2122) message to determine if it’s equal to anObject. Availability Available in iOS 2.0 and later. See Also – allKeys (page 468) – keyEnumerator (page 489) Declared in NSDictionary.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 469allValues Returns a new array containing the dictionary’s values. - (NSArray *)allValues Return Value A new array containing the dictionary’s values, or an empty array if the dictionary has no entries. Discussion The order of the values in the array isn’t defined. Availability Available in iOS 2.0 and later. See Also – allKeys (page 468) – getObjects:andKeys: (page 482) – objectEnumerator (page 493) Declared in NSDictionary.h count Returns the number of entries in the dictionary. - (NSUInteger)count Return Value The number of entries in the dictionary. Availability Available in iOS 2.0 and later. Related Sample Code QuartzDemo Declared in NSDictionary.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 470description Returns a string that represents the contents of the dictionary, formatted as a property list. - (NSString *)description Return Value A string that represents the contents of the dictionary, formatted as a property list. Discussion If each key in the dictionary is an NSString object, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined. This method is intended to produce readable output for debugging purposes, not for serializing data. If you want to store dictionary data for later retrieval, see Property List Programming Guide and Archives and Serializations Programming Guide. Availability Available in iOS 2.0 and later. See Also – descriptionWithLocale: (page 472) – descriptionWithLocale:indent: (page 472) Declared in NSDictionary.h descriptionInStringsFileFormat Returns a string that represents the contents of the dictionary, formatted in .strings file format. - (NSString *)descriptionInStringsFileFormat Return Value A string that represents the contents of the dictionary, formatted in .strings file format. Discussion The order in which the entries are listed is undefined. Availability Available in iOS 2.0 and later. Declared in NSDictionary.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 471descriptionWithLocale: Returns a string object that represents the contents of the dictionary, formatted as a property list. - (NSString *)descriptionWithLocale:(id)locale Parameters locale An object that specifies options used for formatting each of the dictionary’s keys and values; pass nil if you don’t want them formatted. On iOS and Mac OS X v10.5 and later, either an instance of NSDictionary or an NSLocale object may be used for locale. On Mac OS X v10.4 and earlier it must be an instance of NSDictionary. Discussion For a description of how locale is applied to each element in the dictionary, see descriptionWithLocale:indent: (page 472). If each key in the dictionary responds to compare:, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined. Availability Available in iOS 2.0 and later. See Also – description (page 471) – descriptionWithLocale:indent: (page 472) Declared in NSDictionary.h descriptionWithLocale:indent: Returns a string object that represents the contents of the dictionary, formatted as a property list. - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level Parameters locale An object that specifies options used for formatting each of the dictionary’s keys and values; pass nil if you don’t want them formatted. On iOS and Mac OS X v10.5 and later, either an instance of NSDictionary or an NSLocale object may be used for locale. On Mac OS X v10.4 and earlier it must be an instance of NSDictionary. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 472level Specifies 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 object that represents the contents of the dictionary, formatted as a property list. Discussion The returned NSString object contains the string representations of each of the dictionary’s entries. descriptionWithLocale:indent: obtains the string representation of a given key or value as follows: ● If the object is an NSString object, it is used as is. ● If the object responds to descriptionWithLocale:indent:, that method is invoked to obtain the object’s string representation. ● If the object responds to descriptionWithLocale:, that method is invoked to obtain the object’s string representation. ● If none of the above conditions is met, the object’s string representation is obtained by invoking its description method. If each key in the dictionary responds to compare:, the entries are listed in ascending order, by key. Otherwise, the order in which the entries are listed is undefined. Availability Available in iOS 2.0 and later. See Also – description (page 471) – descriptionWithLocale: (page 472) Declared in NSDictionary.h enumerateKeysAndObjectsUsingBlock: Applies a given block object to the entries of the dictionary. - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block Parameters block A block object to operate on entries in the dictionary. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 473Discussion If the block sets *stop to YES, the enumeration stops. Availability Available in iOS 4.0 and later. See Also – enumerateKeysAndObjectsWithOptions:usingBlock: (page 474) Declared in NSDictionary.h enumerateKeysAndObjectsWithOptions:usingBlock: Applies a given block object to the entries of the dictionary. - (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id key, id obj, BOOL *stop))block Parameters opts Enumeration options. block A block object to operate on entries in the dictionary. Discussion If the block sets *stop to YES, the enumeration stops. Availability Available in iOS 4.0 and later. See Also – enumerateKeysAndObjectsUsingBlock: (page 473) Declared in NSDictionary.h fileCreationDate Returns the value for the NSFileCreationDate key. - (NSDate *)fileCreationDate NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 474Return Value The value for the NSFileCreationDate key, or nil if the dictionary doesn’t have an entry for the key. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileExtensionHidden Returns the value for the NSFileExtensionHidden key. - (BOOL)fileExtensionHidden Return Value The value for the NSFileExtensionHidden key, or NO if the dictionary doesn’t have an entry for the key. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileGroupOwnerAccountID Returns the value for the NSFileGroupOwnerAccountID key. - (NSNumber *)fileGroupOwnerAccountID Return Value The value for the NSFileGroupOwnerAccountID key, or nil if the dictionary doesn’t have an entry for the key. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 475fileGroupOwnerAccountName Returns the value for the NSFileGroupOwnerAccountName key. - (NSString *)fileGroupOwnerAccountName Return Value The value for the key NSFileGroupOwnerAccountName, or nil if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the name of the corresponding file’s group. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileHFSCreatorCode Returns the value for the NSFileHFSCreatorCode key. - (OSType)fileHFSCreatorCode Return Value The value for the NSFileHFSCreatorCode key, or 0 if the dictionary doesn’t have an entry for the key. Discussion See “HFS File Types” for details on the OSType data type. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 476fileHFSTypeCode Returns the value for the NSFileHFSTypeCode key. - (OSType)fileHFSTypeCode Return Value The value for the NSFileHFSTypeCode key, or 0 if the dictionary doesn’t have an entry for the key. Discussion See “HFS File Types” for details on the OSType data type. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileIsAppendOnly Returns the value for the NSFileAppendOnly key. - (BOOL)fileIsAppendOnly Return Value The value for the NSFileAppendOnly key, or NO if the dictionary doesn’t have an entry for the key. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileIsImmutable Returns the value for the NSFileImmutable key. - (BOOL)fileIsImmutable Return Value The value for the NSFileImmutable key, or NO if the dictionary doesn’t have an entry for the key. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 477Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileModificationDate Returns the value for the key NSFileModificationDate. - (NSDate *)fileModificationDate Return Value The value for the key NSFileModificationDate, or nil if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the date that the file’s data was last modified. Availability Available in iOS 2.0 and later. Related Sample Code URLCache Declared in NSFileManager.h fileOwnerAccountID Returns the value for the NSFileOwnerAccountID key. - (NSNumber *)fileOwnerAccountID NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 478Return Value The value for the NSFileOwnerAccountID key, or nil if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the account name of the file’s owner. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileOwnerAccountName Returns the value for the key NSFileOwnerAccountName. - (NSString *)fileOwnerAccountName Return Value The value for the key NSFileOwnerAccountName, or nil if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the account name of the file’s owner. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h filePosixPermissions Returns the value for the key NSFilePosixPermissions. - (NSUInteger)filePosixPermissions NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 479Return Value The value, as an unsigned long, for the key NSFilePosixPermissions, or 0 if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the file’s permissions. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileSize Returns the value for the key NSFileSize. - (unsigned long long)fileSize Return Value The value, as an unsigned long long, for the key NSFileSize, or 0 if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary such, as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the file’s size. Special Considerations If the file has a resource fork, the returned value does not include the size of the resource fork. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 480fileSystemFileNumber Returns the value for the key NSFileSystemFileNumber. - (NSUInteger)fileSystemFileNumber Return Value The value, as an unsigned long, for the key NSFileSystemFileNumber, or 0 if the dictionary doesn’t have an entry for the key Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the file’s inode. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h fileSystemNumber Returns the value for the key NSFileSystemNumber. - (NSInteger)fileSystemNumber Return Value The value, as an unsigned long, for the key NSFileSystemNumber, or 0 if the dictionary doesn’t have an entry for the key Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the ID of the device containing the file. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 481fileType Returns the value for the key NSFileType. - (NSString *)fileType Return Value The value for the key NSFileType, or nil if the dictionary doesn’t have an entry for the key. Discussion This and the other file... methods are for use with a dictionary, such as those returned from the methods fileAttributesAtPath:traverseLink: (page 636) (NSFileManager), directoryAttributes (page 500) (NSDirectoryEnumerator), and fileAttributes (page 501) (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the file’s type. Possible return values are described in the “Constants” section of NSFileManager. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h getObjects:andKeys: Returns by reference C arrays of the keys and values in the dictionary. - (void)getObjects:(id *)objects andKeys:(id *)keys Parameters objects Upon return, contains a C array of the values in the dictionary. keys Upon return, contains a C array of the keys in the dictionary. Discussion The elements in the returned arrays are ordered such that the first element in objects is the value for the first key in keys and so on. Availability Available in iOS 2.0 and later. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 482See Also – allKeys (page 468) – allValues (page 470) – objectForKey: (page 494) – objectsForKeys:notFoundMarker: (page 495) Declared in NSDictionary.h initWithContentsOfFile: Initializes a newly allocated dictionary using the keys and values found in a file at a given path. - (id)initWithContentsOfFile:(NSString *)path Parameters path A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary. Return Value An initialized dictionary—which might be different than the original receiver—that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary. Discussion The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable. Availability Available in iOS 2.0 and later. See Also + dictionaryWithContentsOfFile: (page 462) Declared in NSDictionary.h initWithContentsOfURL: Initializes a newly allocated dictionary using the keys and values found at a given URL. - (id)initWithContentsOfURL:(NSURL *)aURL NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 483Parameters aURL An URL that identifies a resource containing a string representation of a property list whose root object is a dictionary. Return Value An initialized dictionary—which might be different than the original receiver—that contains the dictionary at aURL, or nil if there is an error or if the contents of the resource are an invalid representation of a dictionary. Discussion The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable. Availability Available in iOS 2.0 and later. See Also + dictionaryWithContentsOfURL: (page 463) Declared in NSDictionary.h initWithDictionary: Initializes a newly allocated dictionary by placing in it the keys and values contained in another given dictionary. - (id)initWithDictionary:(NSDictionary *)otherDictionary Parameters otherDictionary A dictionary containing the keys and values with which to initialize the new dictionary. Return Value An initialized dictionary—which might be different than the original receiver—containing the keys and values found in otherDictionary. Availability Available in iOS 2.0 and later. See Also + dictionaryWithDictionary: (page 464) NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 484Declared in NSDictionary.h initWithDictionary:copyItems: Initializes a newly allocated dictionary using the objects contained in another given dictionary. - (id)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag Parameters otherDictionary A dictionary containing the keys and values with which to initialize the new dictionary. flag If YES, each object in otherDictionary receives a copyWithZone: (page 1209) message to create a copy of the object—objects must conform to the NSCopying protocol. 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 dictionary. If NO, then in a managed memory environment each object in otherDictionary simply receives a retain message when it is added to the returned dictionary. Return Value An initialized object—which might be different than the original receiver—containing the keys and values found in otherDictionary. Discussion After an immutable dictionary has been initialized in this way, it cannot be modified. The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected. Availability Available in iOS 2.0 and later. See Also – initWithDictionary: (page 484) Declared in NSDictionary.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 485initWithObjects:forKeys: Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays. - (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys Parameters objects An array containing the values for the new dictionary. keys An array containing the keys for the new dictionary. Each key is copied (using copyWithZone: (page 2002); keys must conform to the NSCopying protocol), and the copy is added to the new dictionary. Discussion This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if the objects and keys arrays do not have the same number of elements. Availability Available in iOS 2.0 and later. See Also + dictionaryWithObjects:forKeys: (page 465) – initWithObjects:forKeys:count: (page 486) – initWithObjectsAndKeys: (page 487) Declared in NSDictionary.h initWithObjects:forKeys:count: Initializes a newly allocated dictionary with count entries. - (id)initWithObjects:(id *)objects forKeys:(id *)keys count:(NSUInteger)count Parameters objects A C array of values for the new dictionary. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 486keys A C array of keys for the new dictionary. Each key is copied (using copyWithZone: (page 2002); keys must conform to the NSCopying protocol), and the copy is added to the new dictionary. count The number of elements to use from the keys and objects arrays. count must not exceed the number of elements in objects or keys. Discussion This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if a key or value object is nil. Availability Available in iOS 2.0 and later. See Also + dictionaryWithObjects:forKeys:count: (page 466) – initWithObjects:forKeys: (page 486) – initWithObjectsAndKeys: (page 487) Declared in NSDictionary.h initWithObjectsAndKeys: Initializes a newly allocated dictionary with entries constructed from the specified set of values and keys. - (id)initWithObjectsAndKeys:(id)firstObject , ... Parameters firstObject The first value to add to the new dictionary. ... First the key for firstObject, then a null-terminated list of alternating values and keys. If any key is nil, an NSInvalidArgumentException is raised. Discussion This method is similar to initWithObjects:forKeys: (page 486), differing only in the way in which the key-value pairs are specified. For example: NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 487NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys: @"value1", @"key1", @"value2", @"key2", nil]; Availability Available in iOS 2.0 and later. See Also + dictionaryWithObjectsAndKeys: (page 467) – initWithObjects:forKeys: (page 486) – initWithObjects:forKeys:count: (page 486) Related Sample Code URLCache Declared in NSDictionary.h isEqualToDictionary: Returns a Boolean value that indicates whether the contents of the receiving dictionary are equal to the contents of another given dictionary. - (BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary Parameters otherDictionary The dictionary with which to compare the receiving dictionary. Return Value YES if the contents of otherDictionary are equal to the contents of the receiving dictionary, otherwise NO. Discussion Two dictionaries have equal contents if they each hold the same number of entries and, for a given key, the corresponding value objects in each dictionary satisfy the isEqual: (page 2122) test. Availability Available in iOS 2.0 and later. See Also isEqual: (page 2122) (NSObject protocol) NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 488Declared in NSDictionary.h keyEnumerator Returns an enumerator object that lets you access each key in the dictionary. - (NSEnumerator *)keyEnumerator Return Value An enumerator object that lets you access each key in the dictionary. Discussion The following code fragment illustrates how you might use this method. NSEnumerator *enumerator = [myDictionary keyEnumerator]; id key; while ((key = [enumerator nextObject])) { /* code that uses the returned key */ } If you use this method with instances of mutable subclasses of NSDictionary, your code should not modify the entries during enumeration. If you intend to modify the entries, use the allKeys (page 468) method to create a “snapshot” of the dictionary’s keys. Then use this snapshot to traverse the entries, modifying them along the way. Note that the objectEnumerator (page 493) method provides a convenient way to access each value in the dictionary. Special Considerations 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. Availability Available in iOS 2.0 and later. See Also – allKeys (page 468) – allKeysForObject: (page 469) – getObjects:andKeys: (page 482) NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 489– objectEnumerator (page 493) nextObject (page 505) (NSEnumerator) Declared in NSDictionary.h keysOfEntriesPassingTest: Returns the set of keys whose corresponding value satisfies a constraint described by a block object. - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate Parameters predicate A block object that specifies constraints for values in the dictionary. Return Value The set of keys whose corresponding value satisfies predicate. Availability Available in iOS 4.0 and later. See Also – enumerateKeysAndObjectsUsingBlock: (page 473) Declared in NSDictionary.h keysOfEntriesWithOptions:passingTest: Returns the set of keys whose corresponding value satisfies a constraint described by a block object. - (NSSet *)keysOfEntriesWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate Parameters opts A bit mask of enumeration options. predicate A block object that specifies constraints for values in the dictionary. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 490Return Value The set of keys whose corresponding value satisfies predicate. Availability Available in iOS 4.0 and later. See Also – enumerateKeysAndObjectsWithOptions:usingBlock: (page 474) Declared in NSDictionary.h keysSortedByValueUsingComparator: Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block. - (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr Parameters cmptr A comparator block. Return Value An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using cmptr. Availability Available in iOS 4.0 and later. See Also – keysSortedByValueWithOptions:usingComparator: (page 492) Declared in NSDictionary.h keysSortedByValueUsingSelector: Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values. - (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 491Parameters comparator A selector that specifies the method to use to compare the values in the dictionary. The comparator method should return NSOrderedAscending if the dictionary is smaller than the argument, NSOrderedDescending if the dictionary is larger than the argument, and NSOrderedSame if they are equal. Return Value An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values. Discussion Pairs of dictionary values are compared using the comparison method specified by comparator; the comparator message is sent to one of the values and has as its single argument the other value from the dictionary. Availability Available in iOS 2.0 and later. See Also – allKeys (page 468) sortedArrayUsingSelector: (page 91) (NSArray) Declared in NSDictionary.h keysSortedByValueWithOptions:usingComparator: Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block and a specified set of options. - (NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr Parameters opts A bitmask of sort options. cmptr A comparator block. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 492Return Value An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using cmptr with the options given in opts. Availability Available in iOS 4.0 and later. See Also – keysSortedByValueUsingComparator: (page 491) Declared in NSDictionary.h objectEnumerator Returns an enumerator object that lets you access each value in the dictionary. - (NSEnumerator *)objectEnumerator Return Value An enumerator object that lets you access each value in the dictionary. Discussion The following code fragment illustrates how you might use the method. NSEnumerator *enumerator = [myDictionary objectEnumerator]; id value; while ((value = [enumerator nextObject])) { /* code that acts on the dictionary’s values */ } If you use this method with instances of mutable subclasses of NSDictionary, your code should not modify the entries during enumeration. If you intend to modify the entries, use the allValues (page 470) method to create a “snapshot” of the dictionary’s values. Work from this snapshot to modify the values. Special Considerations 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. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 493Availability Available in iOS 2.0 and later. See Also – keyEnumerator (page 489) nextObject (page 505) (NSEnumerator) Declared in NSDictionary.h objectForKey: Returns the value associated with a given key. - (id)objectForKey:(id)aKey Parameters aKey The key for which to return the corresponding value. Return Value The value associated with aKey, or nil if no value is associated with aKey. Availability Available in iOS 2.0 and later. See Also – allKeys (page 468) – allValues (page 470) – getObjects:andKeys: (page 482) Related Sample Code CryptoExercise International Mountains LocateMe SimpleFTPSample TouchCells Declared in NSDictionary.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 494objectsForKeys:notFoundMarker: Returns the set of objects from the dictionary that corresponds to the specified keys as an NSArray. - (NSArray *)objectsForKeys:(NSArray *)keys notFoundMarker:(id)anObject Parameters keys An NSArray containing the keys for which to return corresponding values. anObject The marker object to place in the corresponding element of the returned array if an object isn’t found in the dictionary to correspond to a given key. Discussion The objects in the returned array and the keys array have a one-for-one correspondence, so that the nthe object in the returned array corresponds to the nthe key in keys. Availability Available in iOS 2.0 and later. See Also – allKeys (page 468) – allValues (page 470) – getObjects:andKeys: (page 482) Declared in NSDictionary.h valueForKey: Returns the value associated with a given key. - (id)valueForKey:(NSString *)key Parameters key The key for which to return the corresponding value. Note that when using key-value coding, the key must be a string (see “Key-Value Coding Fundamentals”). Return Value The value associated with key. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 495Discussion If key does not start with “@”, invokes objectForKey: (page 494). If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key. Availability Available in iOS 2.0 and later. See Also setValue:forKey: (page 991) (NSMutableDictionary) – getObjects:andKeys: (page 482) Related Sample Code GKTank PhotoScroller SeismicXML TheElements Declared in NSKeyValueCoding.h writeToFile:atomically: Writes a property list representation of the contents of the dictionary to a given path. - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag Parameters path The path at which to write the file. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath (page 1634) before invoking this method. flag A flag that specifies whether the file should be written atomically. If flag is YES, the dictionary is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the dictionary 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. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 496Discussion This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) 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. If the dictionary’s contents are all property list objects, the file written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfFile: (page 462) or the instance method initWithContentsOfFile: (page 483). For more information about property lists, see Property List Programming Guide. Availability Available in iOS 2.0 and later. Declared in NSDictionary.h writeToURL:atomically: Writes a property list representation of the contents of the dictionary to a given URL. - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag Parameters aURL The URL to which to write the dictionary. flag A flag that specifies whether the output should be written atomically. If flag is YES, the dictionary is written to an auxiliary location, and then the auxiliary location is renamed to aURL. If flag is NO, the dictionary is written directly to aURL. The YES option guarantees that aURL, if it exists at all, won’t be corrupted even if the system should crash during writing. flag is ignored if aURL is of a type that cannot be written atomically. Return Value YES if the location is written successfully, otherwise NO. Discussion This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant output would not be a valid property list. NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 497If the dictionary’s contents are all property list objects, the location written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfURL: (page 463) or the instance method initWithContentsOfURL: (page 483). For more information about property lists, see Property List Programming Guide. Availability Available in iOS 2.0 and later. Declared in NSDictionary.h NSDictionary Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 498Inherits from NSEnumerator : NSObject Conforms to NSFastEnumeration (NSEnumerator) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSFileManager.h Companion guide Low-Level File Management Programming Topics Overview An NSDirectoryEnumerator object enumerates the contents of a directory, returning the pathnames of all files and directories contained within that directory. These pathnames are relative to the directory. You obtain a directory enumerator using NSFileManager’s enumeratorAtPath: (page 630) method. For more details, see Low-Level File Management Programming Topics. An enumeration is recursive, including the files of all subdirectories, and crosses device boundaries. An enumeration does not resolve symbolic links, or attempt to traverse symbolic links that point to directories. Tasks Getting File and Directory Attributes – directoryAttributes (page 500) Returns an NSDictionary object that contains the attributes of the directory at which enumeration started. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 499 NSDirectoryEnumerator Class Reference– fileAttributes (page 501) Returns an object that contains the attributes of the most recently returned file or subdirectory (as referenced by the pathname). – level (page 501) Returns the number of levels deep the current object is in the directory hierarchy being enumerated. Skipping Subdirectories – skipDescendents (page 502) Causes the receiver to skip recursion into the most recently obtained subdirectory. – skipDescendants (page 501) Causes the receiver to skip recursion into the most recently obtained subdirectory. Instance Methods directoryAttributes Returns an NSDictionary object that contains the attributes of the directory at which enumeration started. - (NSDictionary *)directoryAttributes Return Value An NSDictionary object that contains the attributes of the directory at which enumeration started. Discussion See the description of the fileAttributesAtPath:traverseLink: (page 636) method of NSFileManager for details on obtaining the attributes from the dictionary. Availability Available in iOS 2.0 and later. See Also createDirectoryAtPath:attributes: (page 620) (NSFileManager) Declared in NSFileManager.h NSDirectoryEnumerator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 500fileAttributes Returns an object that contains the attributes of the most recently returned file or subdirectory (as referenced by the pathname). - (NSDictionary *)fileAttributes Return Value A dictionary that contains the attributes of the most recently returned file or subdirectory (as referenced by the pathname). Discussion See the description of the fileAttributesAtPath:traverseLink: (page 636) method of NSFileManager for details on obtaining the attributes from the dictionary. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h level Returns the number of levels deep the current object is in the directory hierarchy being enumerated. - (NSUInteger)level Return Value The number of levels, with the directory passed to enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: (page 632) (NSFileManager) considered to be level 0. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h skipDescendants Causes the receiver to skip recursion into the most recently obtained subdirectory. - (void)skipDescendants NSDirectoryEnumerator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 501Discussion This method is identical to skipDescendents (page 502) except for the spelling. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h skipDescendents Causes the receiver to skip recursion into the most recently obtained subdirectory. - (void)skipDescendents Availability Available in iOS 2.0 and later. See Also – skipDescendants (page 501) Declared in NSFileManager.h NSDirectoryEnumerator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 502Inherits from NSObject Conforms to NSFastEnumeration NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSEnumerator.h Companion guide Collections Programming Topics Related sample code Birthdays Overview NSEnumerator is an abstract class, instances of whose subclasses enumerate collections of other objects, such as arrays and dictionaries. All creation methods are defined in the collection classes—such as NSArray, NSSet, and NSDictionary—which provide special NSEnumerator objects with which to enumerate their contents. For example, NSArray has two methods that return an NSEnumerator object: objectEnumerator (page 1484) and reverseObjectEnumerator (page 86). NSDictionary also has two methods that return an NSEnumerator object: keyEnumerator (page 489) and objectEnumerator (page 493). These methods let you enumerate the contents of a dictionary by key or by value, respectively. You send nextObject (page 505) repeatedly to a newly created NSEnumerator object to have it return the next object in the original collection. When the collection is exhausted, nil is returned. You cannot “reset” an enumerator after it has exhausted its collection. To enumerate a collection again, you need a new enumerator. The enumerator subclasses used by NSArray, NSDictionary, and NSSet retain the collection during enumeration. When the enumeration is exhausted, the collection is released. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 503 NSEnumerator Class ReferenceNote It is not safe to modify a mutable collection while enumerating through it. Some enumerators may currently allow enumeration of a collection that is modified, but this behavior is not guaranteed to be supported in the future. Tasks Getting the Enumerated Objects – allObjects (page 504) Returns an array of objects the receiver has yet to enumerate. – nextObject (page 505) Returns the next object from the collection being enumerated. Instance Methods allObjects Returns an array of objects the receiver has yet to enumerate. - (NSArray *)allObjects Return Value An array of objects the receiver has yet to enumerate. Discussion Put another way, the array returned by this method does not contain objects that have already been enumerated with previous nextObject (page 505) messages. Invoking this method exhausts the enumerator’s collection so that subsequent invocations of nextObject return nil. Availability Available in iOS 2.0 and later. Declared in NSEnumerator.h NSEnumerator Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 504nextObject Returns the next object from the collection being enumerated. - (id)nextObject Return Value The next object from the collection being enumerated, or nil when all objects have been enumerated. Discussion The following code illustrates how this method works using an array: NSArray *anArray = // ... ; NSEnumerator *enumerator = [anArray objectEnumerator]; id object; while ((object = [enumerator nextObject])) { // do something with object... } Availability Available in iOS 2.0 and later. Declared in NSEnumerator.h NSEnumerator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 505Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Declared in Foundation/NSError.h Foundation/NSURLError.h Availability Available in iOS 2.0 and later. Companion guide Error Handling Programming Guide Related sample code iPhoneCoreDataRecipes LazyTableImages SeismicXML TaggedLocations XMLPerformance Overview An NSError object encapsulates richer and more extensible error information than is possible using only an error code or error string. The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information. Several well-known domains are defined corresponding to Mach, POSIX, and OSStatus errors. Foundation error codes are found in the Cocoa error domain and documented in the Foundation Constants Reference. In addition, NSError allows you to attach an arbitrary user info dictionary to an error object, and provides the means to return a human-readable description for the error. NSError is not an abstract class, and can be used directly. Applications may choose to create subclasses of NSError to provide better localized error strings by overriding localizedDescription (page 511). 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 506 NSError Class ReferenceIn general, a method should signal an error condition by—for example—returning NO or nil rather than by the simple presence of an error object. The method can then optionally return an NSError object by reference, in order to further describe the error. NSError is toll-free bridged with its Core Foundation counterpart, CFErrorRef. See “Toll-Free Bridging” for more information. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) Tasks Creating Error Objects + errorWithDomain:code:userInfo: (page 508) Creates and initializes an NSError object for a given domain and code with a given userInfo dictionary. – initWithDomain:code:userInfo: (page 511) Returns an NSError object initialized for a given domain and code with a given userInfo dictionary. Getting Error Properties – code (page 509) Returns the receiver’s error code. – domain (page 510) Returns the receiver’s error domain. – userInfo (page 514) Returns the receiver's user info dictionary. NSError Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 507Getting a Localized Error Description – localizedDescription (page 511) Returns a string containing the localized description of the error. – localizedRecoveryOptions (page 513) Returns an array containing the localized titles of buttons appropriate for displaying in an alert panel. – localizedRecoverySuggestion (page 513) Returns a string containing the localized recovery suggestion for the error. – localizedFailureReason (page 512) Returns a string containing the localized explanation of the reason for the error. Getting the Error Recovery Attempter – recoveryAttempter (page 514) Returns an object that conforms to the NSErrorRecoveryAttempting informal protocol. Displaying a Help Anchor – helpAnchor (page 510) A string to display in response to an alert panel help anchor button being pressed. Class Methods errorWithDomain:code:userInfo: Creates and initializes an NSError object for a given domain and code with a given userInfo dictionary. + (id)errorWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict Parameters domain The error domain—this can be one of the predefined NSError domains, or an arbitrary string describing a custom domain. domain must not be nil. code The error code for the error. NSError Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 508dict The userInfo dictionary for the error. userInfo may be nil. Return Value An NSError object for domain with the specified error code and the dictionary of arbitrary data userInfo. Availability Available in iOS 2.0 and later. Related Sample Code LazyTableImages SeismicXML Declared in NSError.h Instance Methods code Returns the receiver’s error code. - (NSInteger)code Return Value The receiver’s error code. Discussion Note that errors are domain specific. Availability Available in iOS 2.0 and later. See Also – localizedDescription (page 511) – domain (page 510) – userInfo (page 514) Declared in NSError.h NSError Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 509domain Returns the receiver’s error domain. - (NSString *)domain Return Value A string containing the receiver’s error domain. Availability Available in iOS 2.0 and later. See Also – code (page 509) – localizedDescription (page 511) – userInfo (page 514) Declared in NSError.h helpAnchor A string to display in response to an alert panel help anchor button being pressed. - (NSString *)helpAnchor Return Value An NSString that the alert panel will include a help anchor button with that value. Discussion If this method returns a non-nil value for an error being presented by alertWithError:, the alert panel will include a help anchor button that can display this string. The best way to get a value to return for this method is to specify it as the value of NSHelpAnchorErrorKey (page 517) in the NSError object’s userInfo dictionary; or the method can be overridden. Availability Available in iOS 4.0 and later. Declared in NSError.h NSError Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 510initWithDomain:code:userInfo: Returns an NSError object initialized for a given domain and code with a given userInfo dictionary. - (id)initWithDomain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict Parameters domain The error domain—this can be one of the predefined NSError domains, or an arbitrary string describing a custom domain. domain must not be nil. code The error code for the error. dict The userInfo dictionary for the error. userInfo may be nil. Return Value An NSError object initialized for domain with the specified error code and the dictionary of arbitrary data userInfo. Discussion This is the designated initializer for NSError. Availability Available in iOS 2.0 and later. See Also + errorWithDomain:code:userInfo: (page 508) Related Sample Code CryptoExercise Declared in NSError.h localizedDescription Returns a string containing the localized description of the error. - (NSString *)localizedDescription Return Value A string containing the localized description of the error. NSError Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 511By default this method returns the object in the user info dictionary for the key NSLocalizedDescriptionKey. If the user info dictionary doesn’t contain a value for NSLocalizedDescriptionKey, a default string is constructed from the domain and code. Discussion This method can be overridden by subclasses to present customized error strings. Availability Available in iOS 2.0 and later. See Also – code (page 509) – domain (page 510) – userInfo (page 514) Related Sample Code LazyTableImages SeismicXML URLCache Declared in NSError.h localizedFailureReason Returns a string containing the localized explanation of the reason for the error. - (NSString *)localizedFailureReason Return Value A string containing the localized explanation of the reason for the error. By default this method returns the object in the user info dictionary for the key NSLocalizedFailureReasonErrorKey. Discussion This method can be overridden by subclasses to present customized error strings. Availability Available in iOS 2.0 and later. See Also – code (page 509) – domain (page 510) – userInfo (page 514) NSError Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 512Related Sample Code URLCache Declared in NSError.h localizedRecoveryOptions Returns an array containing the localized titles of buttons appropriate for displaying in an alert panel. - (NSArray *)localizedRecoveryOptions Return Value An array containing the localized titles of buttons appropriate for displaying in an alert panel. By default this method returns the object in the user info dictionary for the key NSLocalizedRecoveryOptionsErrorKey. If the user info dictionary doesn’t contain a value for NSLocalizedRecoveryOptionsErrorKey, nil is returned. Discussion The first string is the title of the right-most and default button, the second the one to the left of that, and so on. The recovery options should be appropriate for the recovery suggestion returned by localizedRecoverySuggestion (page 513). If the user info dictionary doesn’t contain a value for NSLocalizedRecoveryOptionsErrorKey, only an OK button is displayed. This method can be overridden by subclasses to present customized recovery suggestion strings. Availability Available in iOS 2.0 and later. Declared in NSError.h localizedRecoverySuggestion Returns a string containing the localized recovery suggestion for the error. - (NSString *)localizedRecoverySuggestion Return Value A string containing the localized recovery suggestion for the error. By default this method returns the object in the user info dictionary for the key NSLocalizedRecoverySuggestionErrorKey. If the user info dictionary doesn’t contain a value for NSLocalizedRecoverySuggestionErrorKey, nil is returned. NSError Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 513Discussion The returned string is suitable for displaying as the secondary message in an alert panel. This method can be overridden by subclasses to present customized recovery suggestion strings. Availability Available in iOS 2.0 and later. Declared in NSError.h recoveryAttempter Returns an object that conforms to the NSErrorRecoveryAttempting informal protocol. - (id)recoveryAttempter Return Value An object that conforms to the NSErrorRecoveryAttempting informal protocol. By default this method returns the object for the user info dictionary for the key NSRecoveryAttempterErrorKey. If the user info dictionary doesn’t contain a value for NSRecoveryAttempterErrorKey, nil is returned. Discussion The recovery attempter must be an object that can correctly interpret an index into the array returned by localizedRecoveryOptions (page 513). Availability Available in iOS 2.0 and later. See Also – localizedRecoveryOptions (page 513) Declared in NSError.h userInfo Returns the receiver's user info dictionary. - (NSDictionary *)userInfo NSError Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 514Return Value The receiver's user info dictionary, or nil if the user info dictionary has not been set. Availability Available in iOS 2.0 and later. See Also – code (page 509) – domain (page 510) – localizedDescription (page 511) Declared in NSError.h Constants User info dictionary keys These keys may exist in the user info dictionary. NSString * const NSLocalizedDescriptionKey; NSString * const NSErrorFailingURLStringKey; NSString * const NSFilePathErrorKey; NSString * const NSStringEncodingErrorKey; NSString * const NSUnderlyingErrorKey; NSString * const NSURLErrorKey; NSString * const NSLocalizedFailureReasonErrorKey; NSString * const NSLocalizedRecoverySuggestionErrorKey; NSString * const NSLocalizedRecoveryOptionsErrorKey; NSString * const NSRecoveryAttempterErrorKey; NSString * const NSHelpAnchorErrorKey; NSString * const NSURLErrorFailingURLErrorKey; NSString * const NSURLErrorFailingURLStringErrorKey; NSString * const NSURLErrorFailingURLPeerTrustErrorKey; Constants NSLocalizedDescriptionKey The corresponding value is a localized string representation of the error that, if present, will be returned by localizedDescription (page 511). Available in iOS 2.0 and later. Declared in NSError.h. NSError Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 515NSErrorFailingURLStringKey The corresponding value is the URL that caused the error. This key is only present in the NSURLErrorDomain. (Deprecated. This constant is deprecated in Mac OS X 10.6, and is superseded by NSURLErrorFailingURLStringErrorKey (page 518).) This constant is deprecated in Mac OS X 10.6, and is superseded by NSURLErrorFailingURLStringErrorKey (page 518). Both constants refer to the same value for backward-compatibility, but the new symbol name has a better prefix. Available in iOS 2.0 and later. Deprecated in iOS 4.0. Declared in NSURLError.h. NSFilePathErrorKey Contains the file path of the error. The corresponding value is an NSString object. Available in iOS 2.0 and later. Declared in NSError.h. NSStringEncodingErrorKey The corresponding value is an NSNumber object containing the NSStringEncoding value. Available in iOS 2.0 and later. Declared in NSError.h. NSUnderlyingErrorKey The corresponding value is an error that was encountered in an underlying implementation and caused the error that the receiver represents to occur. Available in iOS 2.0 and later. Declared in NSError.h. NSURLErrorKey The corresponding value is an NSURL object. Available in iOS 2.0 and later. Declared in NSError.h. NSLocalizedFailureReasonErrorKey The corresponding value is a localized string representation containing the reason for the failure that, if present, will be returned by localizedFailureReason (page 512). This string provides a more detailed explanation of the error than the description. Available in iOS 2.0 and later. Declared in NSError.h. NSError Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 516NSLocalizedRecoverySuggestionErrorKey The corresponding value is a string containing the localized recovery suggestion for the error. This string is suitable for displaying as the secondary message in an alert panel. Available in iOS 2.0 and later. Declared in NSError.h. NSLocalizedRecoveryOptionsErrorKey The corresponding value is an array containing the localized titles of buttons appropriate for displaying in an alert panel. The first string is the title of the right-most and default button, the second the one to the left, and so on. The recovery options should be appropriate for the recovery suggestion returned by localizedRecoverySuggestion (page 513). Available in iOS 2.0 and later. Declared in NSError.h. NSRecoveryAttempterErrorKey The corresponding value is an object that conforms to the NSErrorRecoveryAttempting informal protocol. The recovery attempter must be an object that can correctly interpret an index into the array returned by recoveryAttempter (page 514). Available in iOS 2.0 and later. Declared in NSError.h. NSHelpAnchorErrorKey The corresponding value is an NSString containing the localized help corresponding to the help button. See helpAnchor (page 510) for more information. Available in iOS 4.0 and later. Declared in NSError.h. NSURLErrorFailingURLErrorKey The corresponding value is an NSURL containing the URL which caused a load to fail. This key is only present in the NSURLErrorDomain. Available in iOS 4.0 and later. Declared in NSURLError.h. NSError Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 517NSURLErrorFailingURLStringErrorKey The corresponding value is an NSString object for the URL which caused a load to fail. This key is only present in the NSURLErrorDomain. This constant supersedes NSErrorFailingURLStringKey (page 516), which was deprecated in Mac OS X 10.6. Both constants refer to the same value for backward-compatibility, but this symbol name has a better prefix. Available in iOS 4.0 and later. Declared in NSURLError.h. NSURLErrorFailingURLPeerTrustErrorKey The corresponding value is the SecTrustRef object representing the state of a failed SSL handshake. This key is only present in the NSURLErrorDomain. Available in iOS 3.0 and later. Declared in NSURLError.h. Error Domains The following error domains are predefined. NSString * const NSPOSIXErrorDomain; NSString * const NSOSStatusErrorDomain; NSString * const NSMachErrorDomain; Constants NSPOSIXErrorDomain POSIX/BSD errors Available in iOS 2.0 and later. Declared in NSError.h. NSOSStatusErrorDomain Mac OS 9/Carbon errors Available in iOS 2.0 and later. Declared in NSError.h. NSMachErrorDomain Mach errors Available in iOS 2.0 and later. Declared in NSError.h. Discussion Additionally, the following error domain is defined by Core Foundation: NSError Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 518Defines constants for values returned in the domain field of the CFStreamError structure. CFStreamErrorDomain Declared in NSError.h NSError Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 519Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSException.h Companion guide Exception Programming Topics Related sample code oalTouch Overview NSException is used to implement exception handling and contains information about an exception. An exception is a special condition that interrupts the normal flow of program execution. Each application can interrupt the program for different reasons. For example, one application might interpret saving a file in a directory that is write-protected as an exception. In this sense, the exception is equivalent to an error. Another application might interpret the user’s key-press (for example, Control-C) as an exception: an indication that a long-running process should be aborted. Note The exception handling mechanism uses longjmp to control the flow of execution. Any code written for an application that uses exception handling is therefore subject to the restrictions associated with this functionality. See your compiler documentation for more information on the longjmp function. Adopted Protocols NSCoding 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 520 NSException Class Reference– encodeWithCoder: (page 1999) – initWithCoder: (page 1999) NSCopying – copyWithZone: (page 2002) Tasks Creating and Raising an NSException Object + exceptionWithName:reason:userInfo: (page 522) Creates and returns an exception object . + raise:format: (page 522) A convenience method that creates and raises an exception. + raise:format:arguments: (page 523) Creates and raises an exception with the specified name, reason, and arguments. – initWithName:reason:userInfo: (page 525) Initializes and returns a newly allocated exception object. – raise (page 526) Raises the receiver, causing program flow to jump to the local exception handler. Querying an NSException Object – name (page 526) Returns an NSString object used to uniquely identify the receiver. – reason (page 526) Returns an NSString object containing a “human-readable” reason for the receiver. – userInfo (page 527) Returns an NSDictionary object containing application-specific data pertaining to the receiver. Getting Exception Stack Frames – callStackReturnAddresses (page 524) Returns the call return addresses related to a raised exception. NSException Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 521– callStackSymbols (page 524) Returns an array containing the current call symbols. Class Methods exceptionWithName:reason:userInfo: Creates and returns an exception object . + (NSException *)exceptionWithName:(NSString *)name reason:(NSString *)reason userInfo:(NSDictionary *)userInfo Parameters name The name of the exception. reason A human-readable message string summarizing the reason for the exception. userInfo A dictionary containing user-defined information relating to the exception Return Value The created NSException object or nil if the object couldn't be created. Availability Available in iOS 2.0 and later. See Also – initWithName:reason:userInfo: (page 525) – name (page 526) – reason (page 526) – userInfo (page 527) Declared in NSException.h raise:format: A convenience method that creates and raises an exception. NSException Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 522+ (void)raise:(NSString *)name format:(NSString *)format, ... Parameters name The name of the exception. format, A human-readable message string (that is, the exception reason) with conversion specifications for the variable arguments that follow. ... Variable information to be inserted into the formatted exception reason (in the manner of printf). Discussion The user-defined information is nil for the generated exception object. Availability Available in iOS 2.0 and later. See Also + raise:format:arguments: (page 523) – raise (page 526) Related Sample Code oalTouch Declared in NSException.h raise:format:arguments: Creates and raises an exception with the specified name, reason, and arguments. + (void)raise:(NSString *)name format:(NSString *)format arguments:(va_list)argList Parameters name The name of the exception. format A human-readable message string (that is, the exception reason) with conversion specifications for the variable arguments in argList. argList Variable information to be inserted into the formatted exception reason (in the manner of vprintf). NSException Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 523Discussion The user-defined dictionary of the generated object is nil. Availability Available in iOS 2.0 and later. See Also + raise:format: (page 522) – raise (page 526) Declared in NSException.h Instance Methods callStackReturnAddresses Returns the call return addresses related to a raised exception. - (NSArray *)callStackReturnAddresses Return Value An array of NSNumber objects encapsulating NSUInteger (page 2263) values. Each value is a call frame return address. The array of stack frames starts at the point at which the exception was first raised, with the first items being the most recent stack frames. Discussion NSException subclasses posing as the NSException class or subclasses or other API elements that interfere with the exception-raising mechanism may not get this information. Availability Available in iOS 2.0 and later. Declared in NSException.h callStackSymbols Returns an array containing the current call symbols. - (NSArray *)callStackSymbols NSException Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 524Return Value An array containing the current call stack symbols. Discussion This method returns an array of strings describing the call stack backtrace at the moment the exception was first raised. The format of each string is non-negotiable and is determined by the backtrace_symbols() API Availability Available in iOS 4.0 and later. Declared in NSException.h initWithName:reason:userInfo: Initializes and returns a newly allocated exception object. - (id)initWithName:(NSString *)name reason:(NSString *)reason userInfo:(NSDictionary *)userInfo Parameters name The name of the exception. reason A human-readable message string summarizing the reason for the exception. userInfo A dictionary containing user-defined information relating to the exception Return Value The created NSException object or nil if the object couldn't be created. Discussion This is the designated initializer. Availability Available in iOS 2.0 and later. See Also + exceptionWithName:reason:userInfo: (page 522) Declared in NSException.h NSException Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 525name Returns an NSString object used to uniquely identify the receiver. - (NSString *)name Availability Available in iOS 2.0 and later. See Also + exceptionWithName:reason:userInfo: (page 522) – initWithName:reason:userInfo: (page 525) Declared in NSException.h raise Raises the receiver, causing program flow to jump to the local exception handler. - (void)raise Discussion All other methods that raise an exception invoke this method, so set a breakpoint here if you are debugging exceptions. When there are no exception handlers in the exception handler stack, unless the exception is raised during the posting of a notification, this method calls the uncaught exception handler, in which last-minute logging can be performed. The program then terminates, regardless of the actions taken by the uncaught exception handler. Availability Available in iOS 2.0 and later. See Also + raise:format: (page 522) + raise:format:arguments: (page 523) Declared in NSException.h reason Returns an NSString object containing a “human-readable” reason for the receiver. NSException Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 526- (NSString *)reason Availability Available in iOS 2.0 and later. See Also + exceptionWithName:reason:userInfo: (page 522) – initWithName:reason:userInfo: (page 525) Declared in NSException.h userInfo Returns an NSDictionary object containing application-specific data pertaining to the receiver. - (NSDictionary *)userInfo Discussion Returns nil if no application-specific data exists. As an example, if a method’s return value caused the exception to be raised, the return value might be available to the exception handler through this method. Availability Available in iOS 2.0 and later. See Also + exceptionWithName:reason:userInfo: (page 522) – initWithName:reason:userInfo: (page 525) Declared in NSException.h NSException Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 527Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 3.0 and later. Declared in Foundation/NSExpression.h Companion guide Predicate Programming Guide Overview NSExpression is used to represent expressions in a predicate. Comparison operations in an NSPredicate are based on two expressions, as represented by instances of the NSExpression class. Expressions are created for constant values, key paths, and so on. Generally, anywhere in the NSExpression class hierarchy where there is composite API and subtypes that may only reasonably respond to a subset of that API, invoking a method that does not make sense for that subtype will cause an exception to be thrown. Expression Types In Mac OS X v10.5, NSExpression introduces several new expression types: NSSubqueryExpressionType, NSAggregateExpressionType, NSUnionSetExpressionType, NSIntersectSetExpressionType, and NSMinusSetExpressionType. Aggregate Expressions The aggregate expression allows you to create predicates containing expressions that evaluate to collections that contain further expressions. The collection may be an NSArray, NSSet, or NSDictionary object. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 528 NSExpression Class ReferenceFor example, consider the BETWEEN operator (NSBetweenPredicateOperatorType (page 268)); its right hand side is a collection containing two elements. Using just the Mac OS X v10.4 API, these elements must be constants, as there is no way to populate them using variable expressions. On Mac OS X v10.4, it is not possible to create a predicate template to the effect of date between {$YESTERDAY, $TOMORROW}; instead you must create a new predicate each time. Aggregate expressions are not supported by Core Data. Subquery Expressions The NSSubqueryExpressionType (page 554) creates a sub-expression, evaluation of which returns a subset of a collection of objects. It allows you to create sophisticated queries across relationships, such as a search for multiple correlated values on the destination object of a relationship. Set Expressions The set expressions (NSUnionSetExpressionType (page 554), NSIntersectSetExpressionType (page 554), and NSMinusSetExpressionType (page 554)) combine results in a manner similar to the NSSet methods. Both sides of these expressions must evaluate to a collection; the left-hand side must evaluate to an NSSet object, the right-hand side can be any other collection type. (expression UNION expression) (expression INTERSECT expression) (expression MINUS expression) Set expressions are not supported by Core Data. Function Expressions On Mac OS X v10.4, NSExpression only supports a predefined set of functions: sum, count, min, max, and average. These predefined functions were accessed in the predicate syntax using custom keywords (for example, MAX(1, 5, 10)). On Mac OS X v10.5 and later, function expressions also support arbitrary method invocations. To use this extended functionality, you can now use the syntax FUNCTION(receiver, selectorName, arguments, ...), for example: FUNCTION(@"/Developer/Tools/otest", @"lastPathComponent") => @"otest" NSExpression Class Reference Overview 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 529All methods must take 0 or more id arguments and return an id value, although you can use the CAST expression to convert datatypes with lossy string representations (for example, CAST(####, "NSDate")). The CAST expression is extended in Mac OS X v10.5 to provide support for casting to classes for use in creating receivers for function expressions. Note that although Core Data supports evaluation of the predefined functions, it does not support the evaluation of custom predicate functions in the persistent stores (during a fetch). Tasks Initializing an Expression – initWithExpressionType: (page 549) Initializes the receiver with the specified expression type. Creating an Expression for a Value + expressionForConstantValue: (page 534) Returns a new expression that represents a given constant value. + expressionForEvaluatedObject (page 535) Returns a new expression that represents the object being evaluated. + expressionForKeyPath: (page 542) Returns a new expression that invokes valueForKeyPath: with a given key path. + expressionForVariable: (page 545) Returns a new expression that extracts a value from the variable bindings dictionary for a given key. Creating a Collection Expression + expressionForAggregate: (page 532) Returns a new aggregate expression for a given collection. + expressionForUnionSet:with: (page 545) Returns a new NSExpression object that represent the union of a given set and collection. + expressionForIntersectSet:with: (page 542) Returns a new NSExpression object that represent the intersection of a given set and collection. NSExpression Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 530+ expressionForMinusSet:with: (page 543) Returns a new NSExpression object that represent the subtraction of a given collection from a given set. Creating a Subquery + expressionForSubquery:usingIteratorVariable:predicate: (page 543) Returns an expression that filters a collection by storing elements in the collection in a given variable and keeping the elements for which qualifier returns true. Creating an Expression Using Blocks + expressionForBlock:arguments: (page 533) Creates an NSExpression object that will use the Block for evaluating objects. Creating an Expression for a Function + expressionForFunction:arguments: (page 535) Returns a new expression that will invoke one of the predefined functions. + expressionForFunction:selectorName:arguments: (page 541) Returns an expression which will return the result of invoking on a given target a selector with a given name using given arguments. Getting Information About an Expression – arguments (page 546) Returns the arguments for the receiver. – collection (page 546) Returns the collection of expressions in an aggregate expression, or the collection element of a subquery expression. – constantValue (page 547) Returns the constant value of the receiver. – expressionType (page 548) Returns the expression type for the receiver. NSExpression Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 531– function (page 549) Returns the function for the receiver. – keyPath (page 550) Returns the key path for the receiver. – leftExpression (page 550) Returns the left expression of an aggregate expression. – operand (page 550) Returns the operand for the receiver. – predicate (page 551) Return the predicate of a subquery expression. – rightExpression (page 551) Returns the right expression of an aggregate expression. – variable (page 552) Returns the variable for the receiver. Evaluating an Expression – expressionValueWithObject:context: (page 548) Evaluates an expression using a given object and context. Accessing the Expression Block – expressionBlock (page 547) Returns the expression’s expression Block. Class Methods expressionForAggregate: Returns a new aggregate expression for a given collection. + (NSExpression *)expressionForAggregate:(NSArray *)collection NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 532Parameters collection A collection object (an instance of NSArray, NSSet, or NSDictionary) that contains further expressions. Return Value A new expression that contains the expressions in collection. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForBlock:arguments: Creates an NSExpression object that will use the Block for evaluating objects. + (NSExpression *)expressionForBlock:(id (^)(id evaluatedObject, NSArray *expressions, NSMutableDictionary *context))block arguments:(NSArray *)arguments Parameters block The Block is applied to the object to be evaluated. The Block takes three arguments and returns a value: evaluatedObject The object to be evaluated. expressions An array of predicate expressions that evaluates to a collection. context A dictionary that the expression can use to store temporary state for one predicate evaluation. Note that context is mutable, and that it can only be accessed during the evaluation of the expression. You must not attempt to retain it for use elsewhere. ] The Block returns the evaluatedObject. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 533arguments An array containing NSExpression objects that will be used as parameters during the invocation of selector. For a selector taking no parameters, the array should be empty. For a selector taking one or more parameters, the array should contain one NSExpression object which will evaluate to an instance of the appropriate type for each parameter. If there is a mismatch between the number of parameters expected and the number you provide during evaluation, an exception may be raised or missing parameters may simply be replaced by nil (which occurs depends on how many parameters are provided, and whether you have over- or underflow). See expressionForFunction:arguments: (page 535) for a complete list of arguments. Return Value An expression that filters a collection using the specified Block. Availability Available in iOS 4.0 and later. See Also – expressionBlock (page 547) Declared in NSExpression.h expressionForConstantValue: Returns a new expression that represents a given constant value. + (NSExpression *)expressionForConstantValue:(id)obj Parameters obj The constant value the new expression is to represent. Return Value A new expression that represents the constant value, obj. Availability Available in iOS 3.0 and later. Declared in NSExpression.h NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 534expressionForEvaluatedObject Returns a new expression that represents the object being evaluated. + (NSExpression *)expressionForEvaluatedObject Return Value A new expression that represents the object being evaluated. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForFunction:arguments: Returns a new expression that will invoke one of the predefined functions. + (NSExpression *)expressionForFunction:(NSString *)name arguments:(NSArray *)parameters Parameters name The name of the function to invoke. parameters An array containing NSExpression objects that will be used as parameters during the invocation of selector. For a selector taking no parameters, the array should be empty. For a selector taking one or more parameters, the array should contain one NSExpression object which will evaluate to an instance of the appropriate type for each parameter. If there is a mismatch between the number of parameters expected and the number you provide during evaluation, an exception may be raised or missing parameters may simply be replaced by nil (which occurs depends on how many parameters are provided, and whether you have over- or underflow). Return Value A new expression that invokes the function name using the parameters in parameters. Discussion The name parameter can be one of the following predefined functions. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 535AvailabilityReturnsParameterFunction Mac OS X v10.4 and later An NSNumber object (the average of values in the array) An NSArray object containing NSExpression objects representing numbers average: Mac OS X v10.4 and later An NSNumber object (the sum of values in the array) An NSArray object containing NSExpression objects representing numbers sum: Mac OS X v10.4 and later An NSNumber object (the number of elements in the array) An NSArray object containing NSExpression objects representing numbers count: Mac OS X v10.4 and later An NSNumber object (the minimum of the values in the array) An NSArray object containing NSExpression objects representing numbers min: Mac OS X v10.4 and later An NSNumber object (the maximum of the values in the array) An NSArray object containing NSExpression objects representing numbers max: Mac OS X v10.5 and later An NSNumber object (the median of the values in the array) An NSArray object containing NSExpression objects representing numbers median: Mac OS X v10.5 and later An NSArray object (the mode of the values in the array) An NSArray object containing NSExpression objects representing numbers mode: Mac OS X v10.5 and later An NSNumber object (the standard deviation of the values in the array) An NSArray object containing NSExpression objects representing numbers stddev: Mac OS X v10.5 and later An NSNumber object (the sum of the values in the array) An NSArray object containing two NSExpression objects representing numbers add:to: NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 536AvailabilityReturnsParameterFunction Mac OS X v10.5 and later An NSNumber object (the result of subtracting the second value in the array from the first value in the array) An NSArray object containing two NSExpression objects representing numbers from:subtract: Mac OS X v10.5 and later An NSNumber object (the result of multiplying the values in the array) An NSArray object containing two NSExpression objects representing numbers multiply:by: Mac OS X v10.5 and later An NSNumber object (the result of dividing the first value in the array by the second value in the array) An NSArray object containing two NSExpression objects representing numbers divide:by: Mac OS X v10.5 and later An NSNumber object (the remainder of dividing the first value in the array by the second value in the array) An NSArray object containing two NSExpression objects representing numbers modulus:by: Mac OS X v10.5 and later An NSNumber object (the square root of the value in the array) An NSArray object containing one NSExpression object representing a number sqrt: Mac OS X v10.5 and later An NSNumber object (the log of the value in the array) An NSArray object containing one NSExpression object representing a number log: Mac OS X v10.5 and later An NSNumber object (the natural log of the value in the array) An NSArray object containing one NSExpression object representing a number ln: Mac OS X v10.5 and later An NSNumber object (the result of raising the first value in the array to the power of the second value in the array) An NSArray object containing two NSExpression objects representing numbers raise:toPower: NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 537AvailabilityReturnsParameterFunction Mac OS X v10.5 and later An NSNumber object (the base-e exponential of the value in the array) An NSArray object containing one NSExpression object representing a number exp: Mac OS X v10.5 and later An NSNumber object (the smallest integral value not less than the value in the array) An NSArray object containing one NSExpression object representing a number ceiling: Mac OS X v10.5 and later An NSNumber object (the absolute value of the value in the array) An NSArray object containing one NSExpression object representing a number abs: Mac OS X v10.5 and later An NSNumber object (the integral value nearest to but no greater than the value in the array) An NSArray object containing one NSExpression object representing a number trunc: Mac OS X v10.5 and later An NSNumber object (a random integer value) nilrandom Mac OS X v10.5 and later An NSNumber object (a random integer value between 0 and the value in the array (exclusive)) An NSArray object containing one NSExpression object representing a number random: Mac OS X v10.5 and later An [NSDate] object (the current date and time) nilnow iOS 3.0 and later An NSNumber objectAn NSArray object containing one NSExpression object representing a number floor: iOS 3.0 and later An NSString objectAn NSArray object containing one NSExpression object representing a string uppercase: NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 538AvailabilityReturnsParameterFunction iOS 3.0 and later An NSString objectAn NSArray object containing one NSExpression object representing a string lowercase: iOS 3.0 and later An NSNumber object (the number is treated as an NSInteger) An NSArray object containing two NSExpression objects representing numbers bitwiseAnd:with: iOS 3.0 and later An NSNumber object (the number is treated as an NSInteger) An NSArray object containing two NSExpression objects representing numbers bitwiseOr:with: iOS 3.0 and later An NSNumber object (the number is treated as an NSInteger) An NSArray object containing two NSExpression objects representing numbers bitwiseXor:with: iOS 3.0 and later An NSNumber object (the number is treated as an NSInteger) An NSArray object containing two NSExpression objects representing numbers leftshift:by: iOS 3.0 and later An NSNumber object (the number is treated as an NSInteger) An NSArray object containing two NSExpression objects representing numbers rightshift:by: iOS 3.0 and later An NSNumber object (the number is treated as an NSInteger) An NSArray object containing one NSExpression object representing a number onesComplement: iOS 3.0 and later The result of evaluating the parameter as though the noindex: function expression didn't exist. An NSArray object containing an NSExpression object noindex: This method raises an exception immediately if the selector is invalid; it raises an exception at runtime if the parameters are incorrect. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 539The parameters argument is a collection containing an expression which evaluates to a collection, as illustrated in the following examples: NSNumber *number1 = [NSNumber numberWithInteger:20]; NSNumber *number2 = [NSNumber numberWithInteger:40]; NSArray *numberArray = [NSArray arrayWithObjects: number1, number2, nil]; NSExpression *arrayExpression = [NSExpression expressionForConstantValue: numberArray]; NSArray *argumentArray = [NSArray arrayWithObject: arrayExpression]; NSExpression* expression = [NSExpression expressionForFunction:@"sum:" arguments:argumentArray]; id result = [expression expressionValueWithObject: nil context: nil]; BOOL ok = [result isEqual: [NSNumber numberWithInt: 60]]; // ok == YES [NSExpression expressionForFunction:@"random" arguments:nil]; [NSExpression expressionForFunction:@"max:" arguments: [NSArray arrayWithObject: [NSExpression expressionForConstantValue: [NSArray arrayWithObjects: [NSNumber numberWithInt: 5], [NSNumber numberWithInt: 10], nil]]]]; [NSExpression expressionForFunction:@"subtract:from:" arguments: [NSArray arrayWithObjects: [NSExpression expressionForConstantValue: [NSNumber numberWithInt: 5]], [NSExpression expressionForConstantValue: [NSNumber numberWithInt: 10]], nil]]; Special Considerations This method throws an exception immediately if the selector is unknown; it throws at runtime if the parameters are incorrect. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 540Availability Available in iOS 3.0 and later. See Also + expressionForFunction:selectorName:arguments: (page 541) Declared in NSExpression.h expressionForFunction:selectorName:arguments: Returns an expression which will return the result of invoking on a given target a selector with a given name using given arguments. + (NSExpression *)expressionForFunction:(NSExpression *)target selectorName:(NSString *)name arguments:(NSArray *)parameters Parameters target An NSExpression object which will evaluate an object on which the selector identified by name may be invoked. name The name of the method to be invoked. parameters An array containing NSExpression objects which can be evaluated to provide parameters for the method specified by name. Return Value An expression which will return the result of invoking the selector named name on the result of evaluating the target expression with the parameters specified by evaluating the elements of parameters. Discussion See the description of expressionForFunction:arguments: (page 535) for examples of how to construct the parameter array. Special Considerations This method throws an exception immediately if the selector is unknown; it throws at runtime if the parameters are incorrect. This expression effectively allows your application to invoke any method on any object it can navigate to at runtime. You must consider the security implications of this type of evaluation. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 541Availability Available in iOS 3.0 and later. See Also + expressionForFunction:arguments: (page 535) Declared in NSExpression.h expressionForIntersectSet:with: Returns a new NSExpression object that represent the intersection of a given set and collection. + (NSExpression *)expressionForIntersectSet:(NSExpression *)left with:(NSExpression *)right Parameters left An expression that evaluates to an NSSet object. right An expression that evaluates to a collection object (an instance of NSArray, NSSet, or NSDictionary). Return Value A new NSExpression object that represents the intersection of left and right. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForKeyPath: Returns a new expression that invokes valueForKeyPath: with a given key path. + (NSExpression *)expressionForKeyPath:(NSString *)keyPath Parameters keyPath The key path that the new expression should evaluate. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 542Return Value A new expression that invokes valueForKeyPath: (page 2071) with keyPath. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForMinusSet:with: Returns a new NSExpression object that represent the subtraction of a given collection from a given set. + (NSExpression *)expressionForMinusSet:(NSExpression *)left with:(NSExpression *)right Parameters left An expression that evaluates to an NSSet object. right An expression that evaluates to a collection object (an instance of NSArray, NSSet, or NSDictionary). Return Value A new NSExpression object that represents the subtraction of right from left. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForSubquery:usingIteratorVariable:predicate: Returns an expression that filters a collection by storing elements in the collection in a given variable and keeping the elements for which qualifier returns true. + (NSExpression *)expressionForSubquery:(NSExpression *)expression usingIteratorVariable:(NSString *)variable predicate:(id)predicate Parameters expression A predicate expression that evaluates to a collection. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 543variable Used as a local variable, and will shadow any instances of variable in the bindings dictionary. The variable is removed or the old value replaced once evaluation completes. predicate The predicate used to determine whether the element belongs in the result collection. Return Value An expression that filters a collection by storing elements in the collection in the variable variable and keeping the elements for which qualifier returns true Discussion This method creates a sub-expression, evaluation of which returns a subset of a collection of objects. It allows you to create sophisticated queries across relationships, such as a search for multiple correlated values on the destination object of a relationship. For example, suppose you have an Apartment entity that has a to-many relationship to a Resident entity, and that you want to create a query for all apartments inhabited by a resident whose first name is "Jane" and whose last name is "Doe". Using only API available for Mac OS X v 10.4, you could try the predicate: resident.firstname == "Jane" && resident.lastname == "Doe" but this will always return false since resident.firstname and resident.lastname both return collections. You could also try: resident.firstname CONTAINS "Jane" && resident.lastname CONTAINS "Doe" but this is also flawed—it returns true if there are two residents, one of whom is John Doe and one of whom is Jane Smith. The only way to find the desired apartments is to do two passes: one through residents to find "Jane Doe", and one through apartments to find the ones where our Jane Does reside. Subquery expressions provide a way to encapsulate this type of qualification into a single query. The string format for a subquery expression is: SUBQUERY(collection_expression, variable_expression, predicate); where expression is a predicate expression that evaluates to a collection, variableExpression is an expression which will be used to contain each individual element of collection, and predicate is the predicate used to determine whether the element belongs in the result collection. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 544Using subqueries, the apartment query could be reformulated as (SUBQUERY(residents, $x, $x.firstname == "Jane" && $x.lastname == "Doe").@count != 0) or (SUBQUERY(residents, $x, $x.firstname == "Jane" && $x.lastname == "Doe")[size] != 0) Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForUnionSet:with: Returns a new NSExpression object that represent the union of a given set and collection. + (NSExpression *)expressionForUnionSet:(NSExpression *)left with:(NSExpression *)right Parameters left An expression that evaluates to an NSSet object. right An expression that evaluates to a collection object (an instance of NSArray, NSSet, or NSDictionary). Return Value An new NSExpression object that represents the union of left and right. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionForVariable: Returns a new expression that extracts a value from the variable bindings dictionary for a given key. NSExpression Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 545+ (NSExpression *)expressionForVariable:(NSString *)string Parameters string The key for the variable to extract from the variable bindings dictionary. Return Value A new expression that extracts from the variable bindings dictionary the value for the key string. Availability Available in iOS 3.0 and later. Declared in NSExpression.h Instance Methods arguments Returns the arguments for the receiver. - (NSArray *)arguments Return Value The arguments for the receiver—that is, the array of expressions that will be passed as parameters during invocation of the selector on the operand of a function expression. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h collection Returnsthecollectionofexpressionsinanaggregateexpression,orthecollectionelementofasubqueryexpression. - (id)collection NSExpression Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 546Return Value Returns the collection of expressions in an aggregate expression, or the collection element of a subquery expression. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h constantValue Returns the constant value of the receiver. - (id)constantValue Return Value The constant value of the receiver. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionBlock Returns the expression’s expression Block. - (id, NSArray *, NSMutableDictionary *)expressionBlock Return Value The expression’s expression Block as created in expressionForBlock:arguments: (page 533). Availability Available in iOS 4.0 and later. NSExpression Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 547See Also + expressionForBlock:arguments: (page 533) Declared in NSExpression.h expressionType Returns the expression type for the receiver. - (NSExpressionType)expressionType Return Value The expression type for the receiver. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h expressionValueWithObject:context: Evaluates an expression using a given object and context. - (id)expressionValueWithObject:(id)object context:(NSMutableDictionary *)context Parameters object The object against which the receiver is evaluated. context A dictionary that the expression can use to store temporary state for one predicate evaluation. Can be nil. Note that context is mutable, and that it can only be accessed during the evaluation of the expression. You must not attempt to retain it for use elsewhere. ] Availability Available in iOS 3.0 and later. NSExpression Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 548Declared in NSExpression.h function Returns the function for the receiver. - (NSString *)function Return Value The function for the receiver. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h initWithExpressionType: Initializes the receiver with the specified expression type. - (id)initWithExpressionType:(NSExpressionType)type Parameters type The type of the new expression, as defined by NSExpressionType (page 552). Return Value An initialized NSExpression object of the type type. Special Considerations This method is the designated initializer for NSExpression. Availability Available in iOS 3.0 and later. Declared in NSExpression.h NSExpression Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 549keyPath Returns the key path for the receiver. - (NSString *)keyPath Return Value The key path for the receiver. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h leftExpression Returns the left expression of an aggregate expression. - (NSExpression *)leftExpression Return Value The left expression of a set expression. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h operand Returns the operand for the receiver. - (NSExpression *)operand NSExpression Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 550Return Value The operand for the receiver—that is, the object on which the selector will be invoked. Discussion The object is the result of evaluating a key path or one of the defined functions. This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h predicate Return the predicate of a subquery expression. - (NSPredicate *)predicate Return Value The predicate of a subquery expression. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h rightExpression Returns the right expression of an aggregate expression. - (NSExpression *)rightExpression Return Value The right expression of a set expression. Discussion This method raises an exception if it is not applicable to the receiver. NSExpression Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 551Availability Available in iOS 3.0 and later. Declared in NSExpression.h variable Returns the variable for the receiver. - (NSString *)variable Return Value The variable for the receiver. Discussion This method raises an exception if it is not applicable to the receiver. Availability Available in iOS 3.0 and later. Declared in NSExpression.h Constants NSExpressionType Defines the possible types of NSExpression. NSExpression Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 552enum { NSConstantValueExpressionType = 0, NSEvaluatedObjectExpressionType, NSVariableExpressionType, NSKeyPathExpressionType, NSFunctionExpressionType, NSAggregateExpressionType, NSSubqueryExpressionType = 13, NSUnionSetExpressionType, NSIntersectSetExpressionType, NSMinusSetExpressionType, NSBlockExpressionType = 19 } typedef NSUInteger NSExpressionType; Constants NSConstantValueExpressionType An expression that always returns the same value. Available in iOS 3.0 and later. Declared in NSExpression.h. NSEvaluatedObjectExpressionType An expression that always returns the parameter object itself. Available in iOS 3.0 and later. Declared in NSExpression.h. NSVariableExpressionType An expression that always returns whatever value is associated with the key specified by ‘variable’ in the bindings dictionary. Available in iOS 3.0 and later. Declared in NSExpression.h. NSKeyPathExpressionType An expression that returns something that can be used as a key path. Available in iOS 3.0 and later. Declared in NSExpression.h. NSFunctionExpressionType An expression that returns the result of evaluating a function. Available in iOS 3.0 and later. Declared in NSExpression.h. NSAggregateExpressionType An expression that defines an aggregate of NSExpression objects. Available in iOS 3.0 and later. Declared in NSExpression.h. NSExpression Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 553NSSubqueryExpressionType An expression that filters a collection using a subpredicate. Available in iOS 3.0 and later. Declared in NSExpression.h. NSUnionSetExpressionType An expression that creates a union of the results of two nested expressions. Available in iOS 3.0 and later. Declared in NSExpression.h. NSIntersectSetExpressionType An expression that creates an intersection of the results of two nested expressions. Available in iOS 3.0 and later. Declared in NSExpression.h. NSMinusSetExpressionType An expression that combines two nested expression results by set subtraction. Available in iOS 3.0 and later. Declared in NSExpression.h. NSBlockExpressionType An expression that uses a Block. Available in iOS 4.0 and later. Declared in NSExpression.h. Availability Available in iOS 3.0 and later. Declared in NSExpression.h NSExpression Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 554Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 5.0 and later. Declared in Foundation/NSFileCoordinator.h Overview The NSFileCoordinator class coordinates the reading and writing of files and directories among multiple processes and objects in the same process. You use instances of this class as-is to read from, write to, modify the attributes of, change the location of, or delete a file or directory. Before your code to perform those actions executes, though, the file coordinator lets registered file presenter objects perform any tasks that they might require to ensure their own integrity. For example, if you want to change the location of a file, other objects interested in that file need to know where you intend to move it so that they can update their references. Objects that adopt the NSFilePresenter protocol must register themselves with the NSFileCoordinator class to be notified of any pending changes. They do this by calling the addFilePresenter: (page 557) class method. In a managed memory application, a file presenter must balance calls to addFilePresenter: with a call to removeFilePresenter: (page 558) prior to being released. (In a garbage-collected or ARC-based application, file presenters are removed automatically when they are finalized.) The file presenter class maintains a list of active file presenter objects in the current application and uses that list, plus the file coordinator classes in other processes, to deliver notifications to all of the objects interested in a particular item. Instances of NSFileCoordinator are meant to be used on a per-file-operation basis, where a file operation is something like opening and reading the contents of a file or moving a batch of files and directories to a new location. There is no benefit to keeping a file coordinator object around past the length of the planned operation. In fact, because file coordinators retain file presenter objects, keeping one around could prevent the file presenter objects from being released in a timely manner. For information about implementing a file presenter object to receive file-related notifications, see NSFilePresenter Protocol Reference. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 555 NSFileCoordinator Class ReferenceThreading Considerations Each file coordinator object you create should be used on a single thread only. If you need to coordinate file operations across multiple objects in different threads, each object should create its own file coordinator. Tasks Initializing a File Coordinator – initWithFilePresenter: (page 566) Initializes and returns a file coordinator object using the specified file presenter. Managing File Presenters + addFilePresenter: (page 557) Registers the specified file presenter object so that it can receive notifications. + removeFilePresenter: (page 558) Unregisters the specified file presenter object. + filePresenters (page 558) Returns an array containing the currently registered file presenter objects. Coordinating File Operations – coordinateReadingItemAtURL:options:error:byAccessor: (page 559) Initiates a read operation on a single file or directory using the specified options. – coordinateWritingItemAtURL:options:error:byAccessor: (page 563) Initiates a write operation on a single file or directory using the specified options. – coordinateReadingItemAtURL:options:writingItemAtURL:options:error:byAccessor: (page 561) Initiates a read operation that contains a follow-up write operation. – coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: (page 565) Initiates a write operation that involves a secondary write operation. – prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error:byAccessor: (page 568) Prepare to read or write from multiple files in a single batch operation. NSFileCoordinator Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 556– itemAtURL:didMoveToURL: (page 567) Notifies relevant file presenters that the location of a file or directory changed. – cancel (page 559) Cancels any active file coordination calls. Class Methods addFilePresenter: Registers the specified file presenter object so that it can receive notifications. + (void)addFilePresenter:(id < NSFilePresenter >)filePresenter Parameters filePresenter The file presenter object to register. Discussion This method registers the file presenter object process-wide. Thus, any file coordinator objects you create later automatically know about the file presenter object and know to message it when its file or directory is affected. In a managed memory application—that is, an application that uses retain and release calls—it is your responsibility to balance calls to this method with a corresponding call to the removeFilePresenter: method. You must remove file presenters from the process-wide registry before the object is deallocated. Thus, a file presenter should remove itself in its dealloc method. If your application is garbage collected, file presenters automatically unregister themselves in their finalize method. If you call this method while file operations are already underway in another thread, your file presenter may not receive notifications for that operation. To prevent missing such notifications, create a file coordinator, call its coordinateReadingItemAtURL:options:error:byAccessor: method, and register your file presenter object there. Synchronizing on the presented file or directory guarantees that when your block executes, all other objects have completed any tasks and you have sole access to the item. Availability Available in iOS 5.0 and later. See Also + removeFilePresenter: (page 558) Declared in NSFileCoordinator.h NSFileCoordinator Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 557filePresenters Returns an array containing the currently registered file presenter objects. + (NSArray *)filePresenters Return Value An array of objects that conform to the NSFilePresenter protocol. Availability Available in iOS 5.0 and later. See Also + addFilePresenter: (page 557) + removeFilePresenter: (page 558) Declared in NSFileCoordinator.h removeFilePresenter: Unregisters the specified file presenter object. + (void)removeFilePresenter:(id < NSFilePresenter >)filePresenter Parameters filePresenter The file presenter object to unregister. If the object is not currently registered, this method does nothing. Discussion If your application uses a managed memory model, you must call this method to unregister file presenters before those objects are deallocated. In a garbage-collected application, file presenters are unregistered automatically when they are finalized. Availability Available in iOS 5.0 and later. See Also + addFilePresenter: (page 557) Declared in NSFileCoordinator.h NSFileCoordinator Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 558Instance Methods cancel Cancels any active file coordination calls. - (void)cancel Discussion Use this method to cancel any active calls to coordinate the reading or writing of a file. If the block passed to the file coordination call has not yet been executed—perhaps because the file coordinator is still waiting for a response from other file presenters—the file coordinator method stops waiting for a response, does not execute its block, and returns an error object with the error code NSUserCancelledError (page 2278). However, if the block is already being executed, the file coordinator method does not return until the block finishes executing. You can call this method from any thread of your application and it returns immediately without waiting for the file coordinator object to respond. Thus, when this method returns, you cannot assume that the read or write operation occurred or did not occur. (In fact, it is possible for this method to return while the file coordinator is in the middle of executing a block.) If you want to know whether the operation actually occurred, you must track it yourself by setting a flag when the block starts executing or by using some other means. Availability Available in iOS 5.0 and later. Declared in NSFileCoordinator.h coordinateReadingItemAtURL:options:error:byAccessor: Initiates a read operation on a single file or directory using the specified options. - (void)coordinateReadingItemAtURL:(NSURL *)url options:(NSFileCoordinatorReadingOptions)options error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL))reader Parameters url A URL identifying the file or directory to read. If other objects or processes are acting on the item at the URL, the actual URL passed to reader parameter may be different than the one in this parameter. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 559options One of the reading options described in “NSFileCoordinatorReadingOptions” (page 569). If you pass 0 for this parameter, the savePresentedItemChangesWithCompletionHandler: (page 2047) method of relevant file presenters is called before your block executes. outError On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this read operation, that error is returned in this parameter and the block in the reader parameter is not executed. If you cancel this operation before the reader block is executed, this parameter contains an error object on output. reader A Block object containing the file operations you want to perform in a coordinated manner. This block receives an NSURL object containing the URL of the item and returns no value. Always use the URL passed into the block instead of the value in the url parameter. Discussion You use this method to perform read-related operations on a file or directory in a coordinated manner. This method executes synchronously, blocking the current thread until the reader block finishes executing. Before executing that block, though, the file coordinator waits until other relevant file presenter objects finish in-progress actions. Similarly, your read operation may cause pending actions for other file presenters to wait until your operations are complete. Whether or not the file coordinator waits depends on whether the item being read is a file or directory and also depends on other related operations. ● If the url parameter specifies a file: ● This method waits for other writers of the exact same file to finish in-progress actions. ● This method waits if the file is a file package and other writers are writing to items in the package directory. ● This method does not wait for other readers of the file. ● This method does not wait for writers that are manipulating the parent directory of the file, unless one of those writers specified the NSFileCoordinatorWritingForDeleting (page 570) or NSFileCoordinatorWritingForMoving (page 571) option. ● If the url parameter specifies a directory: ● This method waits if other write operations are occurring on the exact same directory. ● This method does not wait if write operations are occurring on items inside the directory (but not on the directory itself). ● This method does not wait for other readers of the directory. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 560 ● This method does not wait for writers that are manipulating the parent directory of the directory, unless one of those writers specified the NSFileCoordinatorWritingForDeleting (page 570) or NSFileCoordinatorWritingForMoving (page 571) option. This method calls the relinquishPresentedItemToReader: (page 2044) method of any relevant file presenters. This method is called both for file presenters in the current process and in other processes. Depending on the options you specify, other methods of the file presenters may also be called. When reading a file package directory, file presenter objects that are currently reading the contents of that file package also receive these notifications. All of the called methods must return successfully before the file coordinator executes your block. If multiple file presenters are operating on the item, the order in which those presenters are notified is undefined. Do not nest calls to file coordinator methods inside the block you pass to this method. If you call this method or any of the other file coordination methods from inside your block, the file coordinator object throws an exception. If you want to perform a write operation from inside a read block, use the coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: method instead. If you want to perform a batch read operation on multiple files, use the prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error:byAccessor: method. Availability Available in iOS 5.0 and later. See Also – coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: (page 565) – prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error:byAccessor: (page 568) Declared in NSFileCoordinator.h coordinateReadingItemAtURL:options:writingItemAtURL:options:error:byAccessor: Initiates a read operation that contains a follow-up write operation. - (void)coordinateReadingItemAtURL:(NSURL *)readingURL options:(NSFileCoordinatorReadingOptions)readingOptions writingItemAtURL:(NSURL *)writingURL options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void (^)(NSURL *newReadingURL, NSURL *newWritingURL))readerWriter NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 561Parameters readingURL A URL identifying the file or directory to read. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the readerWriter parameter may be different than the one in this parameter. readingOptions One of the reading options described in “NSFileCoordinatorReadingOptions” (page 569). If you pass 0 for this parameter, the savePresentedItemChangesWithCompletionHandler: (page 2047) method of relevant file presenters is called before your block executes. writingURL A URL identifying the file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the readerWriter parameter may be different than the one in this parameter. writingOptions One of the writing options described in “NSFileCoordinatorWritingOptions” (page 570). The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block. outError On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this operation, that error is returned in this parameter and the block in the readerWriter parameter is not executed. If you cancel this operation before the readerWriter block is executed, this parameter contains an error object on output. readerWriter A Block object containing the read and write operations you want to perform in a coordinated manner. This block receives NSURL objects containing the URLs of the items to read and write and returns no value. Always use the URLs passed into the block instead of the values in the readingURL and writingURL parameters. Discussion You use this method to perform a read operation that might also contain a write operation that needs to be coordinated. This method executes synchronously, blocking the current thread until the readerWriter block finishes executing. When performing the write operation, you may call the coordinateWritingItemAtURL:options:error:byAccessor: method from your readerWriter block. This method does the canonical lock ordering that is required to prevent a potential deadlock of the file operations. This method makes the same calls to file presenters, and has the same general wait behavior as the coordinateReadingItemAtURL:options:error:byAccessor: method. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 562Availability Available in iOS 5.0 and later. See Also – coordinateReadingItemAtURL:options:error:byAccessor: (page 559) – coordinateWritingItemAtURL:options:error:byAccessor: (page 563) Declared in NSFileCoordinator.h coordinateWritingItemAtURL:options:error:byAccessor: Initiates a write operation on a single file or directory using the specified options. - (void)coordinateWritingItemAtURL:(NSURL *)url options:(NSFileCoordinatorWritingOptions)options error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL))writer Parameters url A URL identifying the file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to writer parameter may be different than the one in this parameter. options One of the writing options described in “NSFileCoordinatorWritingOptions” (page 570). The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block. outError On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this write operation, that error is returned in this parameter and the block in the writer parameter is not executed. If you cancel this operation before the writer block is executed, this parameter contains an error object on output. writer A Block object containing the file operations you want to perform in a coordinated manner. This block receives an NSURL object containing the URL of the item and returns no value. Always use the URL passed into the block instead of the value in the url parameter. Discussion You use this method to perform write-related operations on a file or directory in a coordinated manner. This method executes synchronously, blocking the current thread until the writer block finishes executing. Before executing the block, though, the file coordinator waits until other relevant file presenter objects finish in-progress NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 563actions. Similarly, your write operation may cause pending actions for other file presenters to wait until your operations are complete. Whether or not the file coordinator waits depends on whether the item being written is a file or directory and also depends on other related operations. ● If the url parameter specifies a file: ● This method waits for other readers and writers of the exact same file to finish in-progress actions. ● This method waits if the file is a file package and other writers are reading or writing items in the package directory. ● This method does not wait for readers or writers that are manipulating the parent directory of the file, unless one of those writers specified the NSFileCoordinatorWritingForDeleting (page 570) or NSFileCoordinatorWritingForMoving (page 571) option. ● If the url parameter specifies a directory: ● This method waits if other read or write operations are occurring on the exact same directory. ● This method does not wait if read or write operations are occurring on items inside the directory (but not on the directory itself). ● This method does not wait for readers or writers that are manipulating the parent directory of the directory, unless one of those writers specified the NSFileCoordinatorWritingForDeleting (page 570) or NSFileCoordinatorWritingForMoving (page 571) option. This method calls the relinquishPresentedItemToWriter: (page 2046) method of any relevant file presenters. This method is called both for file presenters in the current process and in other processes. Depending on the options you specify, other methods of the file presenters may also be called. When writing a file package directory, file presenter objects that are currently reading or writing the contents of that file package also receive these notifications. All of the called methods must return successfully before the file coordinator executes your block. If multiple file presenters are operating on the item, the order in which those presenters are notified is undefined. Note When deleting an item inside a file package using the NSFileCoordinatorWritingForDeleting (page 570) option, the file coordinator does not call the accommodatePresentedItemDeletionWithCompletionHandler: (page 2036) method of any file presenters monitoring the file package directory itself. Instead, the delete operation is treated as a write operation on the file package. With one exception, do not nest calls to file coordinator methods inside the block you pass to this method. You may call the coordinateReadingItemAtURL:options:error:byAccessor: (page 559) method to read the file if you discover through modification-date checking that the contents of the file have changed. However, if you call this method from inside your block, the file coordinator object throws an exception. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 564Availability Available in iOS 5.0 and later. See Also – coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: (page 565) Declared in NSFileCoordinator.h coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: Initiates a write operation that involves a secondary write operation. - (void)coordinateWritingItemAtURL:(NSURL *)url1 options:(NSFileCoordinatorWritingOptions)options1 writingItemAtURL:(NSURL *)url2 options:(NSFileCoordinatorWritingOptions)options2 error:(NSError **)outError byAccessor:(void (^)(NSURL *newURL1, NSURL *newURL2))writer Parameters url1 A URL identifying the first file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the writer parameter may be different than the one in this parameter. options1 One of the writing options described in “NSFileCoordinatorWritingOptions” (page 570). url2 A URL identifying the other file or directory to write. If other objects or processes are acting on the item at the URL, the actual URL passed to the block in the writer parameter may be different than the one in this parameter. options2 One of the writing options described in “NSFileCoordinatorWritingOptions” (page 570). The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block. outError On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this operation, that error is returned in this parameter and the block in the writer parameter is not executed. If you cancel this operation before the writer block is executed, this parameter contains an error object on output. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 565writer A Block object containing the write operations you want to perform in a coordinated manner. This block receives NSURL objects containing the URLs of the items to write and returns no value. Always use the URLs passed into the block instead of the values in the url1 and url2 parameters. Discussion You use this method to perform two write operations without the risk of those operations creating a deadlock. This method executes synchronously, blocking the current thread until the writer block finishes executing. You may call the coordinateWritingItemAtURL:options:error:byAccessor: method from your writer block. This method does the canonical lock ordering that is required to prevent a potential deadlock of the file operations. This method makes the same calls to file presenters, and has the same general wait behavior as the coordinateWritingItemAtURL:options:error:byAccessor: method. Availability Available in iOS 5.0 and later. See Also – coordinateWritingItemAtURL:options:error:byAccessor: (page 563) Declared in NSFileCoordinator.h initWithFilePresenter: Initializes and returns a file coordinator object using the specified file presenter. - (id)initWithFilePresenter:(id < NSFilePresenter >)filePresenterOrNil Parameters filePresenterOrNil The file presenter object that is initiating some action on its file or directory. This object is assumed to be performing the relevant file or directory operations and therefore does not receive notifications about those operations from the returned file coordinator object. This parameter may be nil. Return Value A file coordinator object to use to coordinate file-related operations. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 566Discussion Specifying a file presenter at initialization time is strongly recommended, especially if the file presenter is initiating the file operation. Otherwise, the file presenter itself would receive notifications when it made changes to the file and would have to compensate for that fact. Receiving such notifications could also deadlock too if the file presenter’s code and its notifications run on the same thread. Availability Available in iOS 5.0 and later. Declared in NSFileCoordinator.h itemAtURL:didMoveToURL: Notifies relevant file presenters that the location of a file or directory changed. - (void)itemAtURL:(NSURL *)oldURL didMoveToURL:(NSURL *)newURL Parameters oldURL The old location of the file or directory. newURL The new location of the file or directory. Discussion If you move or rename a file or directory as part of a write operation, call this method to notify relevant file presenters that the change occurred. This method calls the presentedItemDidMoveToURL: (page 2040) method of any relevant file presenters. You must call this method from a block invoked by the coordinateWritingItemAtURL:options:error:byAccessor: (page 563) or coordinateWritingItemAtURL:options:writingItemAtURL:options:error:byAccessor: (page 565) method. Calling this method with the same URL in the oldURL and newURL parameters is harmless. Availability Available in iOS 5.0 and later. Declared in NSFileCoordinator.h NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 567prepareForReadingItemsAtURLs:options:writingItemsAtURLs:options:error: byAccessor: Prepare to read or write from multiple files in a single batch operation. - (void)prepareForReadingItemsAtURLs:(NSArray *)readingURLs options:(NSFileCoordinatorReadingOptions)readingOptions writingItemsAtURLs:(NSArray *)writingURLs options:(NSFileCoordinatorWritingOptions)writingOptions error:(NSError **)outError byAccessor:(void)batchAccessor Parameters readingURLs An array of NSURL objects identifying the items you want to read. readingOptions One of the reading options described in “NSFileCoordinatorReadingOptions” (page 569). If you pass 0 for this parameter, the savePresentedItemChangesWithCompletionHandler: (page 2047) method of relevant file presenters is called before your block executes. writingURLs An array of NSURL objects identifying the items you want to write. writingOptions One of the writing options described in “NSFileCoordinatorWritingOptions” (page 570). The options you specify partially determine how file presenters are notified and how this file coordinator object waits to execute your block. outError On input, a pointer to a pointer for an error object. If a file presenter encounters an error while preparing for this operation, that error is returned in this parameter and the block in the writer parameter is not executed. If you cancel this operation before the batchAccessor block is executed, this parameter contains an error object on output. batchAccessor A Block object containing additional calls to methods of this class. This block receives a completion handler that it must execute when it has finished its read and write calls. Discussion You use this method to prepare the file coordinator for multiple read and write operations. This method executes synchronously, blocking the current thread until the batchAccessor block finishes executing. The block you provide for the batchAccessor parameter does not perform the actual operations itself but calls the coordinateReadingItemAtURL:options:error:byAccessor: and coordinateWritingItemAtURL:options:error:byAccessor: methods to perform them. The reason to call this method first is to improve performance when reading and writing large numbers of files or directories. NSFileCoordinator Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 568Because file coordination requires interprocess communication, it is much more efficient to batch changes to large numbers of files and directories than to change each item individually. The file coordinator uses the values in the readingURLs and writingURLs parameters together with reading and writing options to prepare any relevant file presenters for the upcoming operations. Specifically, it uses these parameters in the same way as the coordinateReadingItemAtURL:options:error:byAccessor: and coordinateWritingItemAtURL:options:error:byAccessor: methods to determine which file presenter methods to call. Availability Available in iOS 5.0 and later. See Also – coordinateReadingItemAtURL:options:error:byAccessor: (page 559) – coordinateWritingItemAtURL:options:error:byAccessor: (page 563) Declared in NSFileCoordinator.h Constants NSFileCoordinatorReadingOptions Options to use when reading the contents or attributes of a file or directory. enum { NSFileCoordinatorReadingWithoutChanges = 1 << 0, NSFileCoordinatorReadingResolvesSymbolicLink = 1 << 1 }; typedef NSUInteger NSFileCoordinatorReadingOptions; Constants NSFileCoordinatorReadingWithoutChanges Specify this constant if your code does not need other objects to save changes first. If you do not specify this constant, the savePresentedItemChangesWithCompletionHandler: (page 2047) method of relevant file presenters is called before your code reads the item. Available in iOS 5.0 and later. Declared in NSFileCoordinator.h. NSFileCoordinator Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 569NSFileCoordinatorReadingResolvesSymbolicLink Specify this constant if you want an item that might be a symbolic link to resolve to the file pointed to by that link (instead of to the link itself). This option applies to the URL passed to the block that handles the actual reading of the item. Available in iOS 5.0 and later. Declared in NSFileCoordinator.h. NSFileCoordinatorWritingOptions Options to use when changing the contents or attributes of a file or directory. enum { NSFileCoordinatorWritingForDeleting = 1 << 0, NSFileCoordinatorWritingForReplacing = 1 << 3, NSFileCoordinatorWritingForMoving = 1 << 1, NSFileCoordinatorWritingForMerging = 1 << 2 }; typedef NSUInteger NSFileCoordinatorWritingOptions; Constants NSFileCoordinatorWritingForDeleting When this constant is specified, the file coordinator calls the accommodatePresentedItemDeletionWithCompletionHandler: (page 2036) method of relevant file presenters to give them a chance to make adjustments before the item is deleted. Available in iOS 5.0 and later. Declared in NSFileCoordinator.h. NSFileCoordinatorWritingForReplacing Specifies whether the act of writing to the file involves actually replacing the file with a different file (or directory). If the current file coordinator is waiting for another object to move or rename the file, this option treats the operation as the creation of a new file (instead of as the replacement of the old file); otherwise, this constant causes the same behavior as the NSFileCoordinatorWritingForDeleting constant. Use this option when the moving or creation of an item would cause the replacement of any existing item. Do not use it when simply updating the contents of the existing file. Available in iOS 5.0 and later. Declared in NSFileCoordinator.h. NSFileCoordinator Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 570NSFileCoordinatorWritingForMoving When specified for a directory item, the file coordinator waits for already running read and write operations of the directory’s contents, that were themselves initiated through a file coordinator, to finish before moving the directory. Queued, but not executing, read and write operations on the directory’s contents wait until the move operation finishes. This option has no effect on files. Available in iOS 5.0 and later. Declared in NSFileCoordinator.h. NSFileCoordinatorWritingForMerging When this constant is specified, the file coordinator calls the savePresentedItemChangesWithCompletionHandler: (page 2047) method of relevant file presenters to give them a chance to save their changes before your code makes its changes. Available in iOS 5.0 and later. Declared in NSFileCoordinator.h. Discussion You must specify only one constant at a time for a given write operation. NSFileCoordinator Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 571Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSFileHandle.h Companion guide Low-Level File Management Programming Topics Related sample code TransWeb Overview The NSFileHandle class is an object-oriented wrapper for a file descriptor. You use file handle objects to access data associated with files, sockets, pipes, and devices. For files, you can read, write, and seek within the file. For sockets, pipes, and devices, you can use a file handle object to monitor the device and process data asynchronously. Most creation methods for NSFileHandle cause the file handle object to take ownership of the associated file descriptor. This means that the file handle object both creates the file descriptor and is responsible for closing it later, usually when the file handle object itself is deallocated. If you want to use a file handle object with a file descriptor that you created, use the initWithFileDescriptor: (page 588) method or use the initWithFileDescriptor:closeOnDealloc: (page 588) method and pass NO for the flag parameter. Run Loop Considerations When using a file handle object to communicate asynchronously with a socket, you must initiate the corresponding operations from a thread with an active run loop. Although the read, accept, and wait operations themselves are performed asynchronously on background threads, the file handle uses a run loop source to monitor the operations and notify your code appropriately. Therefore, you must call those methods from your application’s main thread or from any thread where you have configured a run loop and are using it to process events. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 572 NSFileHandle Class ReferenceFor more information about configuring and using run loops, see Threading Programming Guide. Tasks Getting a File Handle + fileHandleForReadingAtPath: (page 577) Returns a file handle initialized for reading the file, device, or named socket at the specified path. + fileHandleForReadingFromURL:error: (page 578) Returns a file handle initialized for reading the file, device, or named socket at the specified URL. + fileHandleForWritingAtPath: (page 580) Returns a file handle initialized for writing to the file, device, or named socket at the specified path. + fileHandleForWritingToURL:error: (page 581) Returns a file handle initialized for writing to the file, device, or named socket at the specified URL. + fileHandleForUpdatingAtPath: (page 579) Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified path. + fileHandleForUpdatingURL:error: (page 580) Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified URL. + fileHandleWithStandardError (page 583) Returns the file handle associated with the standard error file. + fileHandleWithStandardInput (page 583) Returns the file handle associated with the standard input file. + fileHandleWithStandardOutput (page 584) Returns the file handle associated with the standard output file. + fileHandleWithNullDevice (page 582) Returns a file handle associated with a null device. Creating a File Handle – initWithFileDescriptor: (page 588) Initializes and returns a file handle object associated with the specified file descriptor. NSFileHandle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 573– initWithFileDescriptor:closeOnDealloc: (page 588) Initializes and returns a file handle object associated with the specified file descriptor and deallocation policy. Getting a File Descriptor – fileDescriptor (page 587) Returns the file descriptor associated with the receiver. Reading from a File Handle – availableData (page 586) Returns the data currently available in the receiver. – readDataToEndOfFile (page 591) Synchronously reads the available data up to the end of file or maximum number of bytes. – readDataOfLength: (page 590) Synchronously reads data up to the specified number of bytes. Writing to a File Handle – writeData: (page 597) Synchronously writes the specified data to the receiver. Reading and Writing Using Blocks readabilityHandler (page 576) property The block to use for reading the contents of the file handle asynchronously. writeabilityHandler (page 577) property The block to use for writing the contents of the file handle asynchronously. NSFileHandle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 574Communicating Asynchronously – acceptConnectionInBackgroundAndNotify (page 584) Accepts a socket connection (for stream-type sockets only) in the background and creates a file handle for the “near” (client) end of the communications channel. – acceptConnectionInBackgroundAndNotifyForModes: (page 585) Accepts a socket connection (for stream-type sockets only) in the background and creates a file handle for the “near” (client) end of the communications channel. – readInBackgroundAndNotify (page 591) Reads from the file or communications channel in the background and posts a notification when finished. – readInBackgroundAndNotifyForModes: (page 592) Reads from the file or communications channel in the background and posts a notification when finished. – readToEndOfFileInBackgroundAndNotify (page 593) Reads to the end of file from the file or communications channel in the background and posts a notification when finished. – readToEndOfFileInBackgroundAndNotifyForModes: (page 593) Reads to the end of file from the file or communications channel in the background and posts a notification when finished. – waitForDataInBackgroundAndNotify (page 596) Asynchronously checks to see if data is available. – waitForDataInBackgroundAndNotifyForModes: (page 596) Asynchronously checks to see if data is available. Seeking Within a File – offsetInFile (page 589) Returns the position of the file pointer within the file represented by the receiver. – seekToEndOfFile (page 594) Puts the file pointer at the end of the file referenced by the receiver and returns the new file offset. – seekToFileOffset: (page 594) Moves the file pointer to the specified offset within the file represented by the receiver. NSFileHandle Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 575Operating on a File – closeFile (page 587) Disallows further access to the represented file or communications channel and signals end of file on communications channels that permit writing. – synchronizeFile (page 595) Causes all in-memory data and attributes of the file represented by the receiver to be written to permanent storage. – truncateFileAtOffset: (page 595) Truncates or extends the file represented by the receiver to a specified offset within the file and puts the file pointer at that position. Properties For more about Objective-C properties, see “Properties” in The Objective-C Programming Language. readabilityHandler The block to use for reading the contents of the file handle asynchronously. @property (copy) void (^readabilityHandler)(NSFileHandle *); Discussion The default value of this property is nil. Assigning a valid block object to this property creates a dispatch source for reading the contents of the file or socket. Your block is submitted to the file handle’s dispatch queue when there is data to read. When reading a file, your handler block is typically executed repeatedly until the entire contents of the file have been read. When reading data from a socket, your handler block is executed whenever there is data on the socket waiting to be read. The block you provide must accept a single parameter that is the current file handle. The return type of your block should be void. To stop reading the file or socket, set the value of this property to nil. Doing so cancels the dispatch source and cleans up the file handle’s structures appropriately. Availability Available in iOS 5.0 and later. Declared in NSFileHandle.h NSFileHandle Class Reference Properties 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 576writeabilityHandler The block to use for writing the contents of the file handle asynchronously. @property (copy) void (^writeabilityHandler)(NSFileHandle *); Discussion The default value of this property is nil. Assigning a valid block object to this property creates a dispatch source for writing the contents of the file or socket. Your block is submitted to the file handle’s dispatch queue when there is room available to write more data. When writing a file, your handler block is typically executed repeatedly until the entire contents of the file have been written. When writing data to a socket, your handler block is executed whenever the socket is ready to accept more data. The block you provide must accept a single parameter that is the current file handle. The return type of your block should be void. To stop writing data to the file or socket, set the value of this property to nil. Doing so cancels the dispatch source and cleans up the file handle’s structures appropriately. Availability Available in iOS 5.0 and later. Declared in NSFileHandle.h Class Methods fileHandleForReadingAtPath: Returns a file handle initialized for reading the file, device, or named socket at the specified path. + (id)fileHandleForReadingAtPath:(NSString *)path Parameters path The path to the file, device, or named socket to access. Return Value The initialized file handle object or nil if no file exists at path. Discussion The file pointer is set to the beginning of the file. You cannot write data to the returned file handle object. Use the readDataToEndOfFile or readDataOfLength: methods to read data from it. NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 577When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. See Also – availableData (page 586) – initWithFileDescriptor: (page 588) – readDataOfLength: (page 590) – readDataToEndOfFile (page 591) Related Sample Code TransWeb Declared in NSFileHandle.h fileHandleForReadingFromURL:error: Returns a file handle initialized for reading the file, device, or named socket at the specified URL. + (id)fileHandleForReadingFromURL:(NSURL *)url error:(NSError **)error Parameters url The URL of the file, device, or named socket to access. error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value The initialized file handle object or nil if no file exists at url. Discussion The file pointer is set to the beginning of the file. You cannot write data to the returned file handle object. Use the readDataToEndOfFile or readDataOfLength: methods to read data from it. When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 578Availability Available in iOS 4.0 and later. See Also – availableData (page 586) – initWithFileDescriptor: (page 588) – readDataOfLength: (page 590) – readDataToEndOfFile (page 591) Declared in NSFileHandle.h fileHandleForUpdatingAtPath: Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified path. + (id)fileHandleForUpdatingAtPath:(NSString *)path Parameters path The path to the file, device, or named socket to access. Return Value The initialized file handle object or nil if no file exists at path. Discussion The file pointer is set to the beginning of the file. The returned object responds to both read... messages and writeData: (page 597). When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. See Also – availableData (page 586) – initWithFileDescriptor: (page 588) – readDataOfLength: (page 590) – readDataToEndOfFile (page 591) Declared in NSFileHandle.h NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 579fileHandleForUpdatingURL:error: Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified URL. + (id)fileHandleForUpdatingURL:(NSURL *)url error:(NSError **)error Parameters url The URL of the file, device, or named socket to access. error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value The initialized file handle object or nil if no file exists at url. Discussion The file pointer is set to the beginning of the file. The returned object responds to both NSFileHandleread... messages and writeData: (page 597). When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 4.0 and later. See Also – availableData (page 586) – initWithFileDescriptor: (page 588) – readDataOfLength: (page 590) – readDataToEndOfFile (page 591) – writeData: (page 597) Declared in NSFileHandle.h fileHandleForWritingAtPath: Returns a file handle initialized for writing to the file, device, or named socket at the specified path. + (id)fileHandleForWritingAtPath:(NSString *)path NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 580Parameters path The path to the file, device, or named socket to access. Return Value The initialized file handle object or nil if no file exists at path. Discussion The file pointer is set to the beginning of the file. You cannot read data from the returned file handle object. Use the writeData: method to write data to the file handle. When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. See Also – initWithFileDescriptor: (page 588) – writeData: (page 597) Declared in NSFileHandle.h fileHandleForWritingToURL:error: Returns a file handle initialized for writing to the file, device, or named socket at the specified URL. + (id)fileHandleForWritingToURL:(NSURL *)url error:(NSError **)error Parameters url The URL of the file, device, or named socket to access. error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value The initialized file handle object or nil if no file exists at url. Discussion The file pointer is set to the beginning of the file. The returned object responds only to writeData: (page 597). NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 581When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 4.0 and later. See Also – initWithFileDescriptor: (page 588) – writeData: (page 597) Declared in NSFileHandle.h fileHandleWithNullDevice Returns a file handle associated with a null device. + (id)fileHandleWithNullDevice Return Value A file handle associated with a null device. Discussion You can use null-device file handles as “placeholders” for standard-device file handles or in collection objects to avoid exceptions and other errors resulting from messages being sent to invalid file handles. Read messages sent to a null-device file handle return an end-of-file indicator (an empty NSData object) rather than raise an exception. Write messages are no-ops, whereas fileDescriptor (page 587) returns an illegal value. Other methods are no-ops or return “sensible” values. When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. See Also – initWithFileDescriptor: (page 588) Declared in NSFileHandle.h NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 582fileHandleWithStandardError Returns the file handle associated with the standard error file. + (id)fileHandleWithStandardError Return Value The shared file handle associated with the standard error file. Discussion Conventionally this is a terminal device to which error messages are sent. There is one standard error file handle per process; it is a shared instance. When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. See Also + fileHandleWithNullDevice (page 582) – initWithFileDescriptor: (page 588) Declared in NSFileHandle.h fileHandleWithStandardInput Returns the file handle associated with the standard input file. + (id)fileHandleWithStandardInput Return Value The shared file handle associated with the standard input file. Discussion Conventionally this is a terminal device on which the user enters a stream of data. There is one standard input file handle per process; it is a shared instance. When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. NSFileHandle Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 583See Also + fileHandleWithNullDevice (page 582) – initWithFileDescriptor: (page 588) Declared in NSFileHandle.h fileHandleWithStandardOutput Returns the file handle associated with the standard output file. + (id)fileHandleWithStandardOutput Return Value The shared file handle associated with the standard output file. Discussion Conventionally this is a terminal device that receives a stream of data from a program. There is one standard output file handle per process; it is a shared instance. When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it. Availability Available in iOS 2.0 and later. See Also + fileHandleWithNullDevice (page 582) – initWithFileDescriptor: (page 588) Declared in NSFileHandle.h Instance Methods acceptConnectionInBackgroundAndNotify Accepts a socket connection (for stream-type sockets only) in the background and creates a file handle for the “near” (client) end of the communications channel. - (void)acceptConnectionInBackgroundAndNotify NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 584Discussion This method asynchronously creates a file handle for the other end of the socket connection and returns that object by posting a NSFileHandleConnectionAcceptedNotification (page 599) notification in the current thread. The notification includes a userInfo dictionary with the created NSFileHandle object, which is accessible using the NSFileHandleNotificationFileHandleItem key. You must call this method from a thread that has an active run loop. Special Considerations The receiver must be created by an initWithFileDescriptor: (page 588) message that takes as an argument a stream-type socket created by the appropriate system routine, and that is being listened on. In other words, you must bind() the socket, and ensure that the socket has a connection backlog defined by listen(). The object that will write data to the returned file handle must add itself as an observer of NSFileHandleConnectionAcceptedNotification (page 599). Note that this method does not continue to listen for connection requests after it posts NSFileHandleConnectionAcceptedNotification. If you want to keep getting notified, you need to call acceptConnectionInBackgroundAndNotify again in your observer method. Availability Available in iOS 2.0 and later. See Also enqueueNotification:postingStyle:coalesceMask:forModes: (page 1092) (NSNotificationQueue) – readInBackgroundAndNotify (page 591) – readToEndOfFileInBackgroundAndNotify (page 593) Declared in NSFileHandle.h acceptConnectionInBackgroundAndNotifyForModes: Accepts a socket connection (for stream-type sockets only) in the background and creates a file handle for the “near” (client) end of the communications channel. - (void)acceptConnectionInBackgroundAndNotifyForModes:(NSArray *)modes Parameters modes The runloop modes in which the connection accepted notification can be posted. NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 585Discussion See acceptConnectionInBackgroundAndNotify (page 584) for details of how this method operates. This method differs from acceptConnectionInBackgroundAndNotify (page 584) in that modes specifies the run-loop mode (or modes) in which NSFileHandleConnectionAcceptedNotification (page 599) can be posted. You must call this method from a thread that has an active run loop. Availability Available in iOS 2.0 and later. See Also enqueueNotification:postingStyle:coalesceMask:forModes: (page 1092) (NSNotificationQueue) – readInBackgroundAndNotifyForModes: (page 592) – readToEndOfFileInBackgroundAndNotifyForModes: (page 593) Declared in NSFileHandle.h availableData Returns the data currently available in the receiver. - (NSData *)availableData Return Value The data currently available through the receiver, up to the the maximum size that can be represented by an NSData object. Discussion If the receiver is a file, this method returns the data obtained by reading the file from the current file pointer to the end of the file. If the receiver is a communications channel, this method reads up to a buffer of data and returns it; if no data is available, the method blocks. Returns an empty data object if the end of file is reached. This method raises NSFileHandleOperationException if attempts to determine the file-handle type fail or if attempts to read from the file or channel fail. Availability Available in iOS 2.0 and later. See Also – readDataOfLength: (page 590) – readDataToEndOfFile (page 591) NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 586Declared in NSFileHandle.h closeFile Disallows further access to the represented file or communications channel and signals end of file on communications channels that permit writing. - (void)closeFile Discussion If the file handle object owns its file descriptor, it automatically closes that descriptor when it is deallocated. If you initialized the file handle object using the initWithFileDescriptor: (page 588) method, or you initialized it using the initWithFileDescriptor:closeOnDealloc: (page 588) and passed NO for the flag parameter, you can use this method to close the file descriptor; otherwise, you must close the file descriptor yourself. After calling this method, you may still use the file handle object but must not attempt to read or write data or use the object to operate on the file descriptor. Attempts to read or write a closed file descriptor raise an exception. Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h fileDescriptor Returns the file descriptor associated with the receiver. - (int)fileDescriptor Return Value The POSIX file descriptor associated with the receiver. Discussion You can use this method to retrieve the file descriptor while it is open. If the file handle object owns the file descriptor, you must not close it yourself. However, you can use the closeFile (page 587) method to close the file descriptor programmatically. If you do call the closeFile method, subsequent calls to this method raise an exception. NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 587Availability Available in iOS 2.0 and later. See Also – initWithFileDescriptor: (page 588) Declared in NSFileHandle.h initWithFileDescriptor: Initializes and returns a file handle object associated with the specified file descriptor. - (id)initWithFileDescriptor:(int)fileDescriptor Parameters fileDescriptor The POSIX file descriptor with which to initialize the file handle. This descriptor represents an open file or socket that you created previously. For example, when creating a file handle for a socket, you would pass the value returned by the socket function. Return Value A file handle initialized with fileDescriptor. Discussion The file descriptor you pass in to this method is not owned by the file handle object. Therefore, you are responsible for closing the file descriptor at some point after disposing of the file handle object. You can create a file handle for a socket by using the result of a socket call as fileDescriptor. Availability Available in iOS 2.0 and later. See Also – closeFile (page 587) Declared in NSFileHandle.h initWithFileDescriptor:closeOnDealloc: Initializes and returns a file handle object associated with the specified file descriptor and deallocation policy. NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 588- (id)initWithFileDescriptor:(int)fileDescriptor closeOnDealloc:(BOOL)flag Parameters fileDescriptor The POSIX file descriptor with which to initialize the file handle. flag YES if the returned file handle object should take ownership of the file descriptor and close it for you or NO if you want to maintain ownership of the file descriptor. Return Value An initialized file handle object. Special Considerations If flag is NO, the file descriptor you pass in to this method is not owned by the file handle object. In such a case, you are responsible for closing the file descriptor at some point after disposing of the file handle object. If you want the file handle object to close the descriptor for you automatically, pass YES for the flag parameter. Availability Available in iOS 2.0 and later. See Also – closeFile (page 587) Declared in NSFileHandle.h offsetInFile Returns the position of the file pointer within the file represented by the receiver. - (unsigned long long)offsetInFile Return Value The position of the file pointer within the file represented by the receiver. Special Considerations Raises an exception if the message is sent to a file handle representing a pipe or socket or if the file descriptor is closed. Availability Available in iOS 2.0 and later. NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 589See Also – seekToEndOfFile (page 594) – seekToFileOffset: (page 594) Declared in NSFileHandle.h readDataOfLength: Synchronously reads data up to the specified number of bytes. - (NSData *)readDataOfLength:(NSUInteger)length Parameters length The number of bytes to read from the receiver. Return Value The data available through the receiver up to a maximum of length bytes, or the maximum size that can be represented by an NSData object, whichever is the smaller. Discussion If the receiver is a file, this method returns the data obtained by reading length bytes starting at the current file pointer. If length bytes are not available, this method returns the data from the current file pointer to the end of the file. If the receiver is a communications channel, the method reads up to length bytes from the channel. Returns an empty NSData object if the file is positioned at the end of the file or if an end-of-file indicator is returned on a communications channel. This method raises NSFileHandleOperationException if attempts to determine the file-handle type fail or if attempts to read from the file or channel fail. Availability Available in iOS 2.0 and later. See Also – availableData (page 586) – readDataToEndOfFile (page 591) Declared in NSFileHandle.h NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 590readDataToEndOfFile Synchronously reads the available data up to the end of file or maximum number of bytes. - (NSData *)readDataToEndOfFile Return Value The data available through the receiver up to maximum size that can be represented by an NSData object or, if a communications channel, until an end-of-file indicator is returned. Discussion This method invokes readDataOfLength: (page 590) as part of its implementation. Availability Available in iOS 2.0 and later. See Also – availableData (page 586) Related Sample Code TransWeb Declared in NSFileHandle.h readInBackgroundAndNotify Reads from the file or communications channel in the background and posts a notification when finished. - (void)readInBackgroundAndNotify Discussion This method performs an asynchronous availableData (page 586) operation on a file or communications channel and posts an NSFileHandleReadCompletionNotification (page 600) notification on the current thread when that operation is complete. You must call this method from a thread that has an active run loop. The length of the data is limited to the buffer size of the underlying operating system. The notification includes a userInfo dictionary that contains the data read; access this object using the NSFileHandleNotificationDataItem key. Any object interested in receiving this data asynchronously must add itself as an observer of NSFileHandleReadCompletionNotification (page 600). In communication via stream-type sockets, the receiver is often the object returned in the userInfo dictionary of NSFileHandleConnectionAcceptedNotification (page 599). NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 591Note that this method does not cause a continuous stream of notifications to be sent. If you wish to keep getting notified, you’ll also need to call readInBackgroundAndNotify in your observer method. Availability Available in iOS 2.0 and later. See Also – acceptConnectionInBackgroundAndNotify (page 584) – readToEndOfFileInBackgroundAndNotifyForModes: (page 593) enqueueNotification:postingStyle:coalesceMask:forModes: (page 1092) (NSNotificationQueue) Declared in NSFileHandle.h readInBackgroundAndNotifyForModes: Reads from the file or communications channel in the background and posts a notification when finished. - (void)readInBackgroundAndNotifyForModes:(NSArray *)modes Parameters modes The runloop modes in which the read completion notification can be posted. Discussion See readInBackgroundAndNotify (page 591) for details of how this method operates. This method differs from readInBackgroundAndNotify (page 591) in that modes specifies the run-loop mode (or modes) in which NSFileHandleReadCompletionNotification (page 600) can be posted. You must call this method from a thread that has an active run loop. Availability Available in iOS 2.0 and later. See Also – acceptConnectionInBackgroundAndNotifyForModes: (page 585) enqueueNotification:postingStyle:coalesceMask:forModes: (page 1092) (NSNotificationQueue) Declared in NSFileHandle.h NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 592readToEndOfFileInBackgroundAndNotify Reads to the end of file from the file or communications channel in the background and posts a notification when finished. - (void)readToEndOfFileInBackgroundAndNotify Discussion This method performs an asynchronous readToEndOfFile operation on a file or communications channel and posts an NSFileHandleReadToEndOfFileCompletionNotification (page 601). You must call this method from a thread that has an active run loop. The notification includes a userInfo dictionary that contains the data read; access this object using the NSFileHandleNotificationDataItem key. Any object interested in receiving this data asynchronously must add itself as an observer of NSFileHandleReadToEndOfFileCompletionNotification (page 601). In communication via stream-type sockets, the receiver is often the object returned in the userInfo dictionary of NSFileHandleConnectionAcceptedNotification (page 599). Availability Available in iOS 2.0 and later. See Also – acceptConnectionInBackgroundAndNotify (page 584) – readToEndOfFileInBackgroundAndNotifyForModes: (page 593) enqueueNotification:postingStyle:coalesceMask:forModes: (page 1092) (NSNotificationQueue) Declared in NSFileHandle.h readToEndOfFileInBackgroundAndNotifyForModes: Reads to the end of file from the file or communications channel in the background and posts a notification when finished. - (void)readToEndOfFileInBackgroundAndNotifyForModes:(NSArray *)modes Parameters modes The runloop modes in which the read completion notification can be posted. NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 593Discussion See readToEndOfFileInBackgroundAndNotify (page 593) for details of this method's operation. The method differs from readToEndOfFileInBackgroundAndNotify (page 593) in that modes specifies the run-loop mode (or modes) in which NSFileHandleReadToEndOfFileCompletionNotification (page 601) can be posted. You must call this method from a thread that has an active run loop. Availability Available in iOS 2.0 and later. See Also – acceptConnectionInBackgroundAndNotifyForModes: (page 585) enqueueNotification:postingStyle:coalesceMask:forModes: (page 1092) (NSNotificationQueue) Declared in NSFileHandle.h seekToEndOfFile Puts the file pointer at the end of the file referenced by the receiver and returns the new file offset. - (unsigned long long)seekToEndOfFile Return Value The file offset with the file pointer at the end of the file. This is therefore equal to the size of the file. Special Considerations Raises an exception if the message is sent to an NSFileHandle object representing a pipe or socket or if the file descriptor is closed. Availability Available in iOS 2.0 and later. See Also – offsetInFile (page 589) Declared in NSFileHandle.h seekToFileOffset: Moves the file pointer to the specified offset within the file represented by the receiver. NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 594- (void)seekToFileOffset:(unsigned long long)offset Parameters offset The offset to seek to. Special Considerations Raises an exception if the message is sent to an NSFileHandle object representing a pipe or socket, if the file descriptor is closed, or if any other error occurs in seeking. Availability Available in iOS 2.0 and later. See Also – offsetInFile (page 589) Declared in NSFileHandle.h synchronizeFile Causesallin-memorydataandattributesofthefilerepresentedbythereceivertobewrittentopermanentstorage. - (void)synchronizeFile Discussion This method should be invoked by programs that require the file to always be in a known state. An invocation of this method does not return until memory is flushed. Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h truncateFileAtOffset: Truncates or extends the file represented by the receiver to a specified offset within the file and puts the file pointer at that position. - (void)truncateFileAtOffset:(unsigned long long)offset NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 595Parameters offset The offset within the file that will mark the new end of the file. Discussion If the file is extended (if offset is beyond the current end of file), the added characters are null bytes. Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h waitForDataInBackgroundAndNotify Asynchronously checks to see if data is available. - (void)waitForDataInBackgroundAndNotify Discussion When the data becomes available, this method posts a NSFileHandleDataAvailableNotification (page 600) notification on the current thread. You must call this method from a thread that has an active run loop. Availability Available in iOS 2.0 and later. See Also – waitForDataInBackgroundAndNotifyForModes: (page 596) Declared in NSFileHandle.h waitForDataInBackgroundAndNotifyForModes: Asynchronously checks to see if data is available. - (void)waitForDataInBackgroundAndNotifyForModes:(NSArray *)modes NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 596Parameters modes The runloop modes in which the data available notification can be posted. Discussion When the data becomes available, this method posts a NSFileHandleDataAvailableNotification (page 600) notification on the current thread. This method differs from waitForDataInBackgroundAndNotify (page 596) in that modes specifies the run-loop mode (or modes) in which NSFileHandleDataAvailableNotification (page 600) can be posted. You must call this method from a thread that has an active run loop. Availability Available in iOS 2.0 and later. See Also – waitForDataInBackgroundAndNotify (page 596) Declared in NSFileHandle.h writeData: Synchronously writes the specified data to the receiver. - (void)writeData:(NSData *)data Parameters data The data to be written. Discussion If the receiver is a file, writing takes place at the file pointer’s current position. After it writes the data, the method advances the file pointer by the number of bytes written. This method raises an exception if the file descriptor is closed or is not valid, if the receiver represents an unconnected pipe or socket endpoint, if no free space is left on the file system, or if any other writing error occurs. Availability Available in iOS 2.0 and later. See Also – availableData (page 586) – readDataOfLength: (page 590) NSFileHandle Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 597– readDataToEndOfFile (page 591) Declared in NSFileHandle.h Constants Keys for Notification UserInfo Dictionary Strings that are used as keys in a userinfo dictionary in a file handle notification. NSString * const NSFileHandleNotificationFileHandleItem; NSString * const NSFileHandleNotificationDataItem; Constants NSFileHandleNotificationFileHandleItem A key in the userinfo dictionary in a NSFileHandleConnectionAcceptedNotification (page 599) notification. The corresponding value is the NSFileHandle object representing the “near” end of a socket connection. Available in iOS 2.0 and later. Declared in NSFileHandle.h. NSFileHandleNotificationDataItem A key in the userinfo dictionary in a NSFileHandleReadCompletionNotification (page 600) and NSFileHandleReadToEndOfFileCompletionNotification (page 601). The corresponding value is an NSData object containing the available data read from a socket connection. Available in iOS 2.0 and later. Declared in NSFileHandle.h. Declared in NSFileHandle.h Exception Names Constant that defines the name of a file operation exception. NSFileHandle Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 598extern NSString *NSFileHandleOperationException; Constants NSFileHandleOperationException Raised by NSFileHandle if attempts to determine file-handle type fail or if attempts to read from a file or channel fail. Available in iOS 2.0 and later. Declared in NSFileHandle.h. Declared in NSFileHandle.h Unused Constant Constant that is currently unused. NSString * const NSFileHandleNotificationMonitorModes; Constants NSFileHandleNotificationMonitorModes Currently unused. Available in iOS 2.0 and later. Deprecated in iOS 5.0. Declared in NSFileHandle.h. Declared in NSFileHandle.h Notifications NSFileHandle posts several notifications related to asynchronous background I/O operations. They are set to post when the run loop of the thread that started the asynchronous operation is idle. NSFileHandleConnectionAcceptedNotification ThisnotificationispostedwhenanNSFileHandleobjectestablishesasocketconnectionbetweentwoprocesses, creates an NSFileHandle object for one end of the connection, and makes this object available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either acceptConnectionInBackgroundAndNotify (page 584) or acceptConnectionInBackgroundAndNotifyForModes: (page 585) to an NSFileHandle object representing a server stream-type socket. NSFileHandle Class Reference Notifications 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 599The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information: ValueKey The NSFileHandle object representing the “near” end of a socket connection NSFileHandleNotificationFile- HandleItem An NSNumber object containing an integer representing the UNIX-type error which occurred @"NSFileHandleError" Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h NSFileHandleDataAvailableNotification This notification is posted when the file handle determines that data is currently available for reading in a file or at a communications channel. The observers can then issue the appropriate messages to begin reading the data. To cause the posting of this notification, you must send either waitForDataInBackgroundAndNotify (page 596) or waitForDataInBackgroundAndNotifyForModes: (page 596) to an appropriate NSFileHandle object. The notification object is the NSFileHandle object that sent the notification. This notification does not contain a userInfo dictionary. Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h NSFileHandleReadCompletionNotification This notification is posted when the file handle reads the data currently available in a file or at a communications channel. It makes the data available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either readInBackgroundAndNotify (page 591) or readInBackgroundAndNotifyForModes: (page 592) to an appropriate NSFileHandle object. NSFileHandle Class Reference Notifications 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 600The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information: ValueKey An NSData object containing the available data read from a socket connection NSFileHandleNotificationDataItem An NSNumber object containing an integer representing the UNIX-type error which occurred @"NSFileHandleError" Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h NSFileHandleReadToEndOfFileCompletionNotification This notification is posted when the file handle reads all data in the file or, if a communications channel, until the other process signals the end of data. It makes the data available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either readToEndOfFileInBackgroundAndNotify (page 593) or readToEndOfFileInBackgroundAndNotifyForModes: (page 593) to an appropriate NSFileHandle object. The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information: ValueKey An NSData object containing the available data read from a socket connection NSFileHandleNotificationDataItem An NSNumber object containing an integer representing the UNIX-type error which occurred @"NSFileHandleError" Availability Available in iOS 2.0 and later. Declared in NSFileHandle.h NSFileHandle Class Reference Notifications 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 601Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSFileManager.h Companion guide Low-Level File Management Programming Topics Related sample code AQOfflineRenderTest SimpleFTPSample SimpleNetworkStreams SimpleURLConnections URLCache Overview The NSFileManager class enables you to perform many generic file-system operations and insulates an application from the underlying file system. Most file operations can be performed using the shared file manager object. In iOS and Mac OS X v10.5 and later, you can also create a unique instance of NSFileManager in cases where you want to use a delegate object in conjunction with the file manager. In Cocoa applications, a file manager object is usually your first interaction with the file system. You use this object to locate, create, copy, and move files and directories. You also use this object to get information about files and directories, such as its size, modification date, and BSD permissions. You can also use a file manager object to change the values of many file and directory attributes. The NSFileManager class supports both the NSURL and NSString classes as ways to specify the location of a file or directory. The use of the NSURL class is generally preferred for specifying file-system items because they can convert path information to a more efficient representation internally. You can also obtain a bookmark from an NSURL object, which is similar to an alias and offers a more sure way of locating the file or directory later. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 602 NSFileManager Class ReferenceIf you are moving, copying, linking, or removing files or directories, you can use a delegate in conjunction with a file manager object to manage those operations. The delegate’s role is to affirm the operation and to decide whether to proceed when errors occur. In Mac OS X v10.7 and later, the delegate must conform to the NSFileManagerDelegate protocol. In iOS 5.0 and later and in Mac OS X v10.7 and later, NSFileManager includes methods for managing items stored in the cloud. Files and directories tagged for cloud storage are synced to iCloud so that they can be made available to the user’s iOS devices and Macintosh computers. Changes to an item in one location are propagated to all other locations to ensure the items stay in sync. Threading Considerations The methods of the shared NSFileManager object can be called from multiple threads safely. However, if you use a delegate to receive notifications about the status of move, copy, remove, and link operations, you should create a unique instance of the file manager object, assign your delegate to that object, and use that file manager to initiate your operations. Tasks Creating a File Manager – init (page 641) Returns an initialized NSFileManager instance. + defaultManager (page 609) Returns the shared file manager object for the process. Locating System Directories – URLForDirectory:inDomain:appropriateForURL:create:error: (page 663) Locates and optionally creates the specified common directory in a domain. – URLsForDirectory:inDomains: (page 666) Returns an array of URLs for the specified common directory in the requested domains. NSFileManager Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 603Discovering Directory Contents – contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: (page 616) Performs a shallow search of the specified directory and returns URLs for the contained items. – contentsOfDirectoryAtPath:error: (page 615) Performs a shallow search of the specified directory and returns the paths of any contained items. – enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: (page 632) Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified URL. – enumeratorAtPath: (page 630) Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified path. – mountedVolumeURLsIncludingResourceValuesForKeys:options: (page 648) Returns an array of URLs that identify the mounted volumes available on the computer. – subpathsOfDirectoryAtPath:error: (page 662) Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories. – subpathsAtPath: (page 661) Returns an array of strings identifying the paths for all items in the specified directory. Creating and Deleting Items – createDirectoryAtURL:withIntermediateDirectories:attributes:error: (page 622) Creates a directory with the given attributes at the specified URL. – createDirectoryAtPath:withIntermediateDirectories:attributes:error: (page 621) Creates a directory with given attributes at the specified path. – createFileAtPath:contents:attributes: (page 623) Creates a file with the specified content and attributes at the given location. – removeItemAtURL:error: (page 653) Removes the file or directory at the specified URL. – removeItemAtPath:error: (page 652) Removes the file or directory at the specified path. – replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: (page 654) Replaces the contents of the item at the specified URL in a manner that insures no data loss occurs. NSFileManager Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 604Moving and Copying Items – copyItemAtURL:toURL:error: (page 618) Copies the file at the specified URL to a new location synchronously. – copyItemAtPath:toPath:error: (page 617) Copies the item at the specified path to a new location synchronously. – moveItemAtURL:toURL:error: (page 650) Moves the file or directory at the specified URL to a new location synchronously. – moveItemAtPath:toPath:error: (page 649) Moves the file or directory at the specified path to a new location synchronously. Managing ICloud-Based Items – setUbiquitous:itemAtURL:destinationURL:error: (page 657) Sets whether the item at the specified URL should be stored in the cloud. – startDownloadingUbiquitousItemAtURL:error: (page 659) Starts downloading (if necessary) the specified item to the local system. – isUbiquitousItemAtURL: (page 645) Returns a Boolean indicating whether the item is targeted for storage in iCloud. – URLForUbiquityContainerIdentifier: (page 665) Returns the iCloud directory associated with the specified container ID. – URLForPublishingUbiquitousItemAtURL:expirationDate:error: (page 664) Returns a URL that can be emailed to users to allow them to download a copy of a cloud-based item. – evictUbiquitousItemAtURL:error: (page 635) Removes the local copy of the specified cloud-based item. Creating Symbolic and Hard Links – createSymbolicLinkAtURL:withDestinationURL:error: (page 626) Creates a symbolic link at the specified URL that points to an item at the given URL. – createSymbolicLinkAtPath:withDestinationPath:error: (page 625) Creates a symbolic link that points to the specified destination. – linkItemAtURL:toURL:error: (page 647) Creates a hard link between the items at the specified URLs. NSFileManager Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 605– linkItemAtPath:toPath:error: (page 646) Creates a hard link between the items at the specified paths. – destinationOfSymbolicLinkAtPath:error: (page 628) Returns the path of the item pointed to by a symbolic link. Determining Access to Files – fileExistsAtPath: (page 637) Returns a Boolean value that indicates whether a file or directory exists at a specified path. – fileExistsAtPath:isDirectory: (page 638) Returns a Boolean value that indicates whether a file or directory exists at a specified path. – isReadableFileAtPath: (page 644) Returns a Boolean value that indicates whether the invoking object appears able to read a specified file. – isWritableFileAtPath: (page 646) Returns a Boolean value that indicates whether the invoking object appears able to write to a specified file. – isExecutableFileAtPath: (page 643) Returns a Boolean value that indicates whether the operating system appears able to execute a specified file. – isDeletableFileAtPath: (page 642) Returns a Boolean value that indicates whether the invoking object appears able to delete a specified file. Getting and Setting Attributes – componentsToDisplayForPath: (page 613) Returns an array of strings representing the user-visible components of a given path. – displayNameAtPath: (page 629) Returns the display name of the file or directory at a specified path. – attributesOfItemAtPath:error: (page 610) Returns the attributes of the item at a given path. – attributesOfFileSystemForPath:error: (page 609) Returns a dictionary that describes the attributes of the mounted file system on which a given path resides. NSFileManager Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 606– setAttributes:ofItemAtPath:error: (page 656) Sets the attributes of the specified file or directory. Getting and Comparing File Contents – contentsAtPath: (page 614) Returns the contents of the file at the specified path. – contentsEqualAtPath:andPath: (page 614) Returns a Boolean value that indicates whether the files or directories in specified paths have the same contents. Converting File Paths to Strings – fileSystemRepresentationWithPath: (page 641) Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system. – stringWithFileSystemRepresentation:length: (page 660) Returns an NSString object whose contents are derived from the specified C-string path. Managing the Delegate – setDelegate: (page 657) Sets the delegate for the receiver. – delegate (page 627) Returns the delegate for the receiver. Managing the Current Directory – changeCurrentDirectoryPath: (page 611) Changes the path of the current working directory to the specified path. – currentDirectoryPath (page 627) Returns the path of the program’s current directory. NSFileManager Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 607Deprecated Methods – changeFileAttributes:atPath: (page 612) Deprecated in iOS 2.0 Changes the attributes of a given file or directory. (Deprecated. Use setAttributes:ofItemAtPath:error: (page 656) instead.) – createDirectoryAtPath:attributes: (page 620) Deprecated in iOS 2.0 Creates a directory (without contents) at a given path with given attributes. (Deprecated. Use createDirectoryAtURL:withIntermediateDirectories:attributes:error: (page 622) instead.) – createSymbolicLinkAtPath:pathContent: (page 624) Deprecated in iOS 2.0 Creates a symbolic link identified by a given path that refers to a given location. (Deprecated. Use createSymbolicLinkAtURL:withDestinationURL:error: (page 626) instead.) – directoryContentsAtPath: (page 628) Deprecated in iOS 2.0 Returns the directories and files (including symbolic links) contained in a given directory. (Deprecated. Use contentsOfDirectoryAtPath:error: (page 615) instead.) – fileAttributesAtPath:traverseLink: (page 636) Deprecated in iOS 2.0 Returns a dictionary that describes the POSIX attributes of the file specified at a given. (Deprecated. Use attributesOfItemAtPath:error: (page 610) instead.) – fileSystemAttributesAtPath: (page 640) Deprecated in iOS 2.0 Returns a dictionary that describes the attributes of the mounted file system on which a given path resides. (Deprecated. Use attributesOfFileSystemForPath:error: (page 609) instead.) – pathContentOfSymbolicLinkAtPath: (page 652) Deprecated in iOS 2.0 Returns the path of the directory or file that a symbolic link at a given path refers to. (Deprecated. Use destinationOfSymbolicLinkAtPath:error: (page 628) instead.) – fileManager:shouldProceedAfterError: (page 667) delegate method Deprecated in iOS 2.0 An NSFileManager object sends this message to its handler for each error it encounters when copying, moving, removing, or linking files or directories. (Deprecated. See delegate methods for copy, move, remove, and link methods.) – fileManager:willProcessPath: (page 669) delegate method Deprecated in iOS 2.0 An NSFileManager object sends this message to a handler immediately before attempting to move, copy, rename, or delete, or before attempting to link to a given path. (Deprecated. See delegate methods for copy, move, link, and remove methods.) NSFileManager Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 608Class Methods defaultManager Returns the shared file manager object for the process. + (NSFileManager *)defaultManager Return Value The default NSFileManager object for the file system. Discussion This method always returns the same file manager object. If you plan to use a delegate with the file manager to receive notifications about the completion of file-based operations, you should create a new instance of NSFileManager (using the init (page 641) method) rather than using the shared object. Availability Available in iOS 2.0 and later. Related Sample Code AQOfflineRenderTest iPhoneCoreDataRecipes iPhoneExtAudioFileConvertTest SimpleNetworkStreams URLCache Declared in NSFileManager.h Instance Methods attributesOfFileSystemForPath:error: Returns a dictionary that describes the attributes of the mounted file system on which a given path resides. - (NSDictionary *)attributesOfFileSystemForPath:(NSString *)path error:(NSError **)error Parameters path Any pathname within the mounted file system. NSFileManager Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 609error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value An NSDictionary object that describes the attributes of the mounted file system on which path resides. See “File-System Attribute Keys” (page 678) for a description of the keys available in the dictionary. Discussion This method does not traverse a terminal symbolic link. Availability Available in iOS 2.0 and later. See Also – attributesOfItemAtPath:error: (page 610) – setAttributes:ofItemAtPath:error: (page 656) Declared in NSFileManager.h attributesOfItemAtPath:error: Returns the attributes of the item at a given path. - (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error Parameters path The path of a file or directory. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value An NSDictionary object that describes the attributes (file, directory, symlink, and so on) of the file specified by path. The keys in the dictionary are described in “File Attribute Keys” (page 672). NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 610Special Considerations This method does not traverse symbolic links. If the item at the path is a symbolic link—that is, the value of the NSFileType key in the attributes dictionary is NSFileTypeSymbolicLink (page 677)—you can use the destinationOfSymbolicLinkAtPath:error: (page 628) method to retrieve the path of the item pointed to by the link. You can also use the stringByResolvingSymlinksInPath (page 1639) method of NSString to resolve links in the path before retrieving the item’s attributes. As a convenience, NSDictionary provides a set of methods (declared as a category on NSDictionary) for quickly and efficiently obtaining attribute information from the returned dictionary: fileGroupOwnerAccountName (page 476), fileModificationDate (page 478), fileOwnerAccountName (page 479), filePosixPermissions (page 479), fileSize (page 480), fileSystemFileNumber (page 481), fileSystemNumber (page 481), and fileType (page 482). Availability Available in iOS 2.0 and later. See Also – setAttributes:ofItemAtPath:error: (page 656) Related Sample Code SimpleFTPSample SimpleNetworkStreams SimpleURLConnections URLCache Declared in NSFileManager.h changeCurrentDirectoryPath: Changes the path of the current working directory to the specified path. - (BOOL)changeCurrentDirectoryPath:(NSString *)path Parameters path The path of the directory to which to change. Return Value YES if successful, otherwise NO. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 611Discussion All relative pathnames refer implicitly to the current working directory. Changing the current working directory affects only paths created in the current process. Availability Available in iOS 2.0 and later. See Also – currentDirectoryPath (page 627) – fileExistsAtPath:isDirectory: (page 638) – contentsOfDirectoryAtPath:error: (page 615) Declared in NSFileManager.h changeFileAttributes:atPath: Changes the attributes of a given file or directory. (Deprecated in iOS 2.0. Use setAttributes:ofItemAtPath:error: (page 656) instead.) - (BOOL)changeFileAttributes:(NSDictionary *)attributes atPath:(NSString *)path Parameters attributes A dictionary containing as keys the attributes to set for path and as values the corresponding value for the attribute. You can set following: NSFileBusy, NSFileCreationDate, NSFileExtensionHidden, NSFileGroupOwnerAccountID, NSFileGroupOwnerAccountName, NSFileHFSCreatorCode, NSFileHFSTypeCode, NSFileImmutable, NSFileModificationDate, NSFileOwnerAccountID, NSFileOwnerAccountName, NSFilePosixPermissions. You can change single attributes or any combination of attributes; you need not specify keys for all attributes. For the NSFilePosixPermissions value, specify a file mode from the OR’d permission bit masks defined in sys/stat.h. See the man page for the chmod function (man 2 chmod) for an explanation. path A path to a file or directory. Return Value YES if all changes succeed. If any change fails, returns NO, but it is undefined whether any changes actually occurred. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 612Discussion As in the POSIX standard, the application either must own the file or directory or must be running as superuser for attribute changes to take effect. The method attempts to make all changes specified in attributes and ignores any rejection of an attempted modification. The NSFilePosixPermissions value must be initialized with the code representing the POSIX file-permissions bit pattern. NSFileHFSCreatorCode and NSFileHFSTypeCode will only be heeded when path specifies a file. Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use setAttributes:ofItemAtPath:error: (page 656) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – attributesOfItemAtPath:error: (page 610) – setAttributes:ofItemAtPath:error: (page 656) Declared in NSFileManager.h componentsToDisplayForPath: Returns an array of strings representing the user-visible components of a given path. - (NSArray *)componentsToDisplayForPath:(NSString *)path Parameters path A pathname. Return Value An array of NSString objects representing the user-visible (for the Finder, Open and Save panels, and so on) components of path. Returns nil if path does not exist. Discussion These components cannot be used for path operations and are only suitable for display to the user. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 613Availability Available in iOS 2.0 and later. Declared in NSFileManager.h contentsAtPath: Returns the contents of the file at the specified path. - (NSData *)contentsAtPath:(NSString *)path Parameters path The path of the file whose contents you want. Return Value An NSData object with the contents of the file. If path specifies a directory, or if some other error occurs, this method returns nil. Availability Available in iOS 2.0 and later. See Also – contentsEqualAtPath:andPath: (page 614) – createFileAtPath:contents:attributes: (page 623) Declared in NSFileManager.h contentsEqualAtPath:andPath: Returns a Boolean value that indicates whether the files or directories in specified paths have the same contents. - (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2 Parameters path1 The path of a file or directory to compare with the contents of path2. path2 The path of a file or directory to compare with the contents of path1. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 614Return Value YES if file or directory specified in path1 has the same contents as that specified in path2, otherwise NO. Discussion If path1 and path2 are directories, the contents are the list of files and subdirectories each contains—contents of subdirectories are also compared. For files, this method checks to see if they’re the same file, then compares their size, and finally compares their contents. This method does not traverse symbolic links, but compares the links themselves. Availability Available in iOS 2.0 and later. See Also – contentsAtPath: (page 614) Declared in NSFileManager.h contentsOfDirectoryAtPath:error: Performs a shallow search of the specified directory and returns the paths of any contained items. - (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error Parameters path The path to the directory whose contents you want to enumerate. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value An array of NSString objects, each of which identifies a file, directory, or symbolic link contained in path. Returns an empty array if the directory exists but has no contents. If an error occurs, this method returns nil and assigns an appropriate error object to the error parameter NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 615Discussion This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”), or resource forks (files that begin with “._”) but it does return other hidden files (files that begin with a period character). If you need to perform a deep enumeration, use the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: (page 632) method instead. The order of the files in the returned array is undefined. Availability Available in iOS 2.0 and later. See Also – currentDirectoryPath (page 627) – fileExistsAtPath:isDirectory: (page 638) – enumeratorAtPath: (page 630) – subpathsAtPath: (page 661) Declared in NSFileManager.h contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: Performs a shallow search of the specified directory and returns URLs for the contained items. - (NSArray *)contentsOfDirectoryAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys options:(NSDirectoryEnumerationOptions)mask error:(NSError **)error Parameters url The URL for the directory whose contents you want to enumerate. keys An array of keys that identify the file properties that you want pre-fetched for each item in the directory. For each returned URL, the specified properties are fetched and cached in the NSURL object. For a list of keys you can specify, see Common File System Resource Keys (page 1824). mask Options for the enumeration. Because this method performs only shallow enumerations, the only supported option is NSDirectoryEnumerationSkipsHiddenFiles (page 671). NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 616error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value An array of NSURL objects, each of which identifies a file, directory, or symbolic link contained in url. If the directory contains no entries, this method returns an empty array. If an error occurs, this method returns nil and assigns an appropriate error object to the error parameter. Discussion This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”), or resource forks (files that begin with “._”) but it does return other hidden files (files that begin with a period character). If you need to perform a deep enumeration, use the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: (page 632) method instead. The order of the files in the returned array is undefined. Availability Available in iOS 4.0 and later. See Also – contentsOfDirectoryAtPath:error: (page 615) Declared in NSFileManager.h copyItemAtPath:toPath:error: Copies the item at the specified path to a new location synchronously. - (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error Parameters srcPath The path to the file or directory you want to move. This parameter must not be nil. dstPath The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 617error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the item was copied successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred. Discussion When copying items, the current process must have permission to read the file or directory at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method copies the directory and all of its contents, including any hidden files. If a file with the same name already exists at dstPath, this method aborts the copy attempt and returns an appropriate error. If the last component of srcPath is a symbolic link, only the link is copied to the new path. Prior to copying an item, the file manager asks its delegate if it should actually do so for each item. It does this by calling the fileManager:shouldCopyItemAtURL:toURL: (page 2018) method; if that method is not implemented it calls the fileManager:shouldCopyItemAtPath:toPath: (page 2017) method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager copies the given file or directory. If there is an error copying an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: (page 2023) or fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: (page 2022) method to determine how to proceed. Availability Available in iOS 2.0 and later. Related Sample Code CoreDataBooks iPhoneCoreDataRecipes XMLPerformance Declared in NSFileManager.h copyItemAtURL:toURL:error: Copies the file at the specified URL to a new location synchronously. - (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 618Parameters srcURL The file URL that identifies the file you want to copy. The URL in this parameter must not be a file reference URL. This parameter must not be nil. dstURL The URL at which to place the copy of srcURL. The URL in this parameter must not be a file reference URL and must include the name of the file in its new location. This parameter must not be nil. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the item was copied successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred. Discussion When copying items, the current process must have permission to read the file or directory at srcURL and write the parent directory of dstURL. If the item at srcURL is a directory, this method copies the directory and all of its contents, including any hidden files. If a file with the same name already exists at dstURL, this method aborts the copy attempt and returns an appropriate error. If the last component of srcURL is a symbolic link, only the link is copied to the new path. Prior to copying each item, the file manager asks its delegate if it should actually do so. It does this by calling the fileManager:shouldCopyItemAtURL:toURL: (page 2018) method; if that method is not implemented (or the process is running in Mac OS X 10.5 or earlier) it calls the fileManager:shouldCopyItemAtPath:toPath: (page 2017) method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager proceeds to copy the file or directory. If there is an error copying an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:copyingItemAtURL:toURL: (page 2023) or fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: (page 2022) method to determine how to proceed. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 619createDirectoryAtPath:attributes: Creates a directory (without contents) at a given path with given attributes. (Deprecated in iOS 2.0. Use createDirectoryAtURL:withIntermediateDirectories:attributes:error: (page 622) instead.) - (BOOL)createDirectoryAtPath:(NSString *)path attributes:(NSDictionary *)attributes Parameters path The path at which to create the new directory. The directory to be created must not yet exist, but its parent directory must exist. attributes The file attributes for the new directory. The attributes you can set are owner and group numbers, file permissions, and modification date. If you specify nil for attributes, default values for these attributes are set (particularly write access for the creator and read access for others). The “Constants” (page 670) section lists the global constants used as keys in the attributes dictionary. Some of the keys, such as NSFileHFSCreatorCode and NSFileHFSTypeCode, do not apply to directories. Return Value YES if the operation was successful or the directory already exists, otherwise NO. Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use createDirectoryAtPath:withIntermediateDirectories:attributes:error: (page 621) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – createDirectoryAtPath:withIntermediateDirectories:attributes:error: (page 621) – changeCurrentDirectoryPath: (page 611) – setAttributes:ofItemAtPath:error: (page 656) – createFileAtPath:contents:attributes: (page 623) – currentDirectoryPath (page 627) Declared in NSFileManager.h NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 620createDirectoryAtPath:withIntermediateDirectories:attributes:error: Creates a directory with given attributes at the specified path. - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error Parameters path A path string identifying the directory to create. You may specify a full path or a path that is relative to the current working directory. This parameter must not be nil. createIntermediates If YES, this method creates any non-existent parent directories as part of creating the directory in url. If NO, this method fails if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory. attributes The file attributes for the new directory and any newly created intermediate directories. You can set the owner and group numbers, file permissions, and modification date. If you specify nil for this parameter or omit a particular value, one or more default values are used as described in the discussion. For a list of keys you can include in this dictionary, see “Constants” (page 670) section lists the global constants used as keys in the attributes dictionary. Some of the keys, such as NSFileHFSCreatorCode and NSFileHFSTypeCode, do not apply to directories. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the directory was created or already exists or NO if an error occurred. Discussion If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created directories are as follows: ● Permissions are set according to the umask of the current process. For more information, see umask. ● The owner ID is set to the effective user ID of the process. ● The group ID is set to that of the parent directory. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 621Availability Available in iOS 2.0 and later. See Also – createDirectoryAtURL:withIntermediateDirectories:attributes:error: (page 622) – setAttributes:ofItemAtPath:error: (page 656) Declared in NSFileManager.h createDirectoryAtURL:withIntermediateDirectories:attributes:error: Creates a directory with the given attributes at the specified URL. - (BOOL)createDirectoryAtURL:(NSURL *)url withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error Parameters url A file URL that specifies the directory to create. If you want to specify a relative path, you must set the current working directory before creating the corresponding NSURL object. This parameter must not be nil. createIntermediates If YES, this method creates any non-existent parent directories as part of creating the directory in url. If NO, this method fails if any of the intermediate parent directories does not exist. attributes The file attributes for the new directory. You can set the owner and group numbers, file permissions, and modification date. If you specify nil for this parameter, the directory is created according to the umask(2) Mac OS X Developer Tools Manual Page of the process. The “Constants” (page 670) section lists the global constants used as keys in the attributes dictionary. Some of the keys, such as NSFileHFSCreatorCode and NSFileHFSTypeCode, do not apply to directories. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the directory was created or already exists or NO if an error occurred. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 622Discussion If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created directories are as follows: ● Permissions are set according to the umask of the current process. For more information, see umask. ● The owner ID is set to the effective user ID of the process. ● The group ID is set to that of the parent directory. If you want to specify a relative path for url, you must set the current working directory before creating the corresponding NSURL object. Availability Available in iOS 5.0 and later. See Also – createDirectoryAtPath:withIntermediateDirectories:attributes:error: (page 621) – setAttributes:ofItemAtPath:error: (page 656) Declared in NSFileManager.h createFileAtPath:contents:attributes: Creates a file with the specified content and attributes at the given location. - (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)contents attributes:(NSDictionary *)attributes Parameters path The path for the new file. contents A data object containing the contents of the new file. attributes A dictionary containing the attributes to associate with the new file. You can use these attributes to set the owner and group numbers, file permissions, and modification date. For a list of keys, see “File Attribute Keys” (page 672). If you specify nil for attributes, the file is created with a set of default attributes. Return Value YES if the operation was successful, otherwise NO. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 623Discussion If you specify nil for the attributes parameter, this method uses a default set of values for the owner, group, and permissions of any newly created directories in the path. Similarly, if you omit a specific attribute, the default value is used. The default values for newly created files are as follows: ● Permissions are set according to the umask of the current process. For more information, see umask. ● The owner ID is set to the effective user ID of the process. ● The group ID is set to that of the parent directory. If a file already exists at path, this method overwrites the contents of that file if the current process has the appropriate privileges to do so. Availability Available in iOS 2.0 and later. See Also – contentsAtPath: (page 614) – setAttributes:ofItemAtPath:error: (page 656) – setAttributes:ofItemAtPath:error: (page 656) – attributesOfItemAtPath:error: (page 610) Related Sample Code URLCache Declared in NSFileManager.h createSymbolicLinkAtPath:pathContent: Creates a symbolic link identified by a given path that refers to a given location. (Deprecated in iOS 2.0. Use createSymbolicLinkAtURL:withDestinationURL:error: (page 626) instead.) - (BOOL)createSymbolicLinkAtPath:(NSString *)path pathContent:(NSString *)otherPath Parameters path The path for a symbolic link. otherPath The path to which path should refer. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 624Return Value YES if the operation is successful, otherwise NO. Returns NO if a file, directory, or symbolic link identical to path already exists. Discussion Creates a symbolic link identified by path that refers to the location otherPath in the file system. Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use createSymbolicLinkAtPath:withDestinationPath:error: (page 625) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – createSymbolicLinkAtPath:withDestinationPath:error: (page 625) – destinationOfSymbolicLinkAtPath:error: (page 628) – removeItemAtPath:error: (page 652) Declared in NSFileManager.h createSymbolicLinkAtPath:withDestinationPath:error: Creates a symbolic link that points to the specified destination. - (BOOL)createSymbolicLinkAtPath:(NSString *)path withDestinationPath:(NSString *)destPath error:(NSError **)error Parameters path The path at which to create the new symbolic link. The last path component is used as the name of the link. destPath The path that contains the item to be pointed to by the link. In other words, this is the destination of the link. error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 625Return Value YES if the symbolic link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at path. Discussion This method does not traverse symbolic links contained in either path or destPath. Availability Available in iOS 2.0 and later. See Also – destinationOfSymbolicLinkAtPath:error: (page 628) – removeItemAtPath:error: (page 652) Declared in NSFileManager.h createSymbolicLinkAtURL:withDestinationURL:error: Creates a symbolic link at the specified URL that points to an item at the given URL. - (BOOL)createSymbolicLinkAtURL:(NSURL *)url withDestinationURL:(NSURL *)destURL error:(NSError **)error Parameters url The file URL at which to create the new symbolic link. The last path component of the URL issued as the name of the link. destURL The file URL that contains the item to be pointed to by the link. In other words, this is the destination of the link. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the symbolic link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at path. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 626Discussion This method does not traverse symbolic links contained in either url or destURL. Availability Available in iOS 5.0 and later. See Also – createSymbolicLinkAtPath:withDestinationPath:error: (page 625) Declared in NSFileManager.h currentDirectoryPath Returns the path of the program’s current directory. - (NSString *)currentDirectoryPath Return Value The path of the program’s current directory. If the program’s current working directory isn’t accessible, returns nil. Discussion The string returned by this method is initialized to the current working directory; you can change the working directory by invoking changeCurrentDirectoryPath: (page 611). Relative pathnames refer implicitly to the current directory. For example, if the current directory is /tmp, and the relative pathname reports/info.txt is specified, the resulting full pathname is /tmp/reports/info.txt. Availability Available in iOS 2.0 and later. See Also – changeCurrentDirectoryPath: (page 611) – createDirectoryAtPath:withIntermediateDirectories:attributes:error: (page 621) Declared in NSFileManager.h delegate Returns the delegate for the receiver. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 627- (id)delegate Return Value The delegate for the receiver. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h destinationOfSymbolicLinkAtPath:error: Returns the path of the item pointed to by a symbolic link. - (NSString *)destinationOfSymbolicLinkAtPath:(NSString *)path error:(NSError **)error Parameters path The path of a file or directory. error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value An NSString object containing the path of the directory or file to which the symbolic link path refers, or nil upon failure. If the symbolic link is specified as a relative path, that relative path is returned. Availability Available in iOS 2.0 and later. See Also – createSymbolicLinkAtPath:withDestinationPath:error: (page 625) Declared in NSFileManager.h directoryContentsAtPath: Returns the directories and files (including symbolic links) contained in a given directory. (Deprecated in iOS 2.0. Use contentsOfDirectoryAtPath:error: (page 615) instead.) NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 628- (NSArray *)directoryContentsAtPath:(NSString *)path Parameters path A path to a directory. Return Value An array of NSString objects identifying the directories and files (including symbolic links) contained in path. Returns an empty array if the directory exists but has no contents. Returns nil if the directory specified at path does not exist or there is some other error accessing it. Discussion The search is shallow and therefore does not return the contents of any subdirectories. This returned array does not contain strings for the current directory (“.”), parent directory (“..”), or resource forks (begin with “._”) and does not traverse symbolic links. Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use contentsOfDirectoryAtPath:error: (page 615) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – contentsOfDirectoryAtPath:error: (page 615) – currentDirectoryPath (page 627) – fileExistsAtPath:isDirectory: (page 638) – enumeratorAtPath: (page 630) – subpathsAtPath: (page 661) Declared in NSFileManager.h displayNameAtPath: Returns the display name of the file or directory at a specified path. - (NSString *)displayNameAtPath:(NSString *)path NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 629Parameters path The path of a file or directory. Return Value The name of the file or directory at path in a localized form appropriate for presentation to the user. If there is no file or directory at path, or if an error occurs, returns path as is. Discussion Display names are user-friendly names for files. They are typically used to localize standard file and directory names according to the user’s language settings. They may also reflect other modifications, such as the removal of filename extensions. Such modifications are used only when displaying the file or directory to the user and do not reflect the actual path to the item in the file system. For example, if the current user’s preferred language is French, the following code fragment logs the name Bibliothèque and not the name Library, which is the actual name of the directory. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); if ([paths count] > 0) { NSString *documentsDirectory = [paths objectAtIndex:0]; NSFileManager *fileManager = [[NSFileManager alloc] init]; NSString *displayNameAtPath = [fileManager displayNameAtPath:documentsDirectory]; NSLog(@"%@", displayNameAtPath); [fileManager release]; } Availability Available in iOS 2.0 and later. Declared in NSFileManager.h enumeratorAtPath: Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified path. - (NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 630Parameters path The path of the directory to enumerate. Return Value An NSDirectoryEnumerator object that enumerates the contents of the directory at path. If path is a filename, the method returns an enumerator object that enumerates no files—the first call to nextObject (page 505) will return nil. Discussion Because the enumeration is deep—that is, it lists the contents of all subdirectories—this enumerator object is useful for performing actions that involve large file-system subtrees. This method does not resolve symbolic links encountered in the traversal process, nor does it recurse through them if they point to a directory. This code fragment enumerates the subdirectories and files under a user’s Documents directory and processes all files with an extension of .doc: NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"]; NSFileManager *localFileManager=[[NSFileManager alloc] init]; NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir]; NSString *file; while (file = [dirEnum nextObject]) { if ([[file pathExtension] isEqualToString: @"doc"]) { // process the document [self scanDocument: [docsDir stringByAppendingPathComponent:file]]; } } [localFileManager release]; The NSDirectoryEnumerator class has methods for obtaining the attributes of the existing path and of the parent directory and for skipping descendants of the existing path. Availability Available in iOS 2.0 and later. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 631See Also – currentDirectoryPath (page 627) – attributesOfItemAtPath:error: (page 610) – contentsOfDirectoryAtPath:error: (page 615) – subpathsAtPath: (page 661) – enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: (page 632) Declared in NSFileManager.h enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified URL. - (NSDirectoryEnumerator *)enumeratorAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys options:(NSDirectoryEnumerationOptions)mask errorHandler:(BOOL (^)(NSURL *url, NSError *error))handler Parameters url The location of the directory for which you want an enumeration. This URL must not be a symbolic link that points to the desired directory. You can use the URLByResolvingSymlinksInPath (page 1822) method to resolve any symlinks in the URL. keys An array of keys that identify the properties that you want pre-fetched for each item in the enumeration. The values for these keys are cached in the corresponding NSURL objects. You may specify nil for this parameter. For a list of keys you can specify, see Common File System Resource Keys (page 1824). mask Options for the enumeration. For a list of valid options, see “Directory Enumeration Options” (page 671). handler An optional 'errorHandler' block argument to call when an error occurs. The url parameter specifies the item for which the error occurred and the error parameter contains the error information. Your handler should return YES when it wants the enumeration to continue or NO when it wants the enumeration to stop. Return Value An NSDirectoryEnumerator object that enumerates the contents of the directory at url. If url is a filename, the method returns an enumerator object that enumerates no files—the first call to nextObject (page 505) returns nil. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 632Discussion Because the enumeration is deep—that is, it lists the contents of all subdirectories—this enumerator object is useful for performing actions that involve large file-system subtrees. If the method is passed a directory on which another file system is mounted (a mount point), it traverses the mount point. This method does not resolve symbolic links encountered in the traversal process, nor does it recurse through them if they point to a directory. The NSDirectoryEnumerator class has methods for skipping descendants of the existing path and for returning the number of levels deep the current object is in the directory hierarchy being enumerated (where the directory passed to enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: is considered to be level 0). This code fragment enumerates a URL and it’s subdirectories, collecting the URLs of files (skips directories). It also demonstrates how to ignore the contents of specified directories, in this case directories named “_extras”. -(void)scanURLIgnoringExtras:(NSURL *)directoryToScan { // Create a local file manager instance NSFileManager *localFileManager=[[NSFileManager alloc] init]; // Enumerate the directory (specified elsewhere in your code) // Request the two properties the method uses, name and isDirectory // Ignore hidden files // The errorHandler: parameter is set to nil. Typically you'd want to present a panel NSDirectoryEnumerator *dirEnumerator = [localFileManager enumeratorAtURL:directoryToScan includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey,nil] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil]; // An array to store the all the enumerated file names in NSMutableArray *theArray=[NSMutableArray array]; // Enumerate the dirEnumerator results, each value is stored in allURLs for (NSURL *theURL in dirEnumerator) { NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 633// Retrieve the file name. From NSURLNameKey, cached during the enumeration. NSString *fileName; [theURL getResourceValue:&fileName forKey:NSURLNameKey error:NULL]; // Retrieve whether a directory. From NSURLIsDirectoryKey, also // cached during the enumeration. NSNumber *isDirectory; [theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; // Ignore files under the _extras directory if (([fileName caseInsensitiveCompare:@"_extras"]==NSOrderedSame) && ([isDirectory boolValue]==YES)) { [dirEnumerator skipDescendants]; } else { // Add full path for non directories if ([isDirectory boolValue]==NO) [theArray addObject:theURL]; } } // Do something with the path URLs. NSLog(@"theArray - %@",theArray); // Release the localFileManager. [localFileManager release]; } Availability Available in iOS 4.0 and later. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 634See Also – enumeratorAtPath: (page 630) Declared in NSFileManager.h evictUbiquitousItemAtURL:error: Removes the local copy of the specified cloud-based item. - (BOOL)evictUbiquitousItemAtURL:(NSURL *)url error:(NSError **)errorOut Parameters url Specify the URL to a file or directory in iCloud storage. errorOut On input, a pointer to variable for an NSError object. If an error occurs, this pointer is set to an NSError object containing information about the error. You may specify nil for this parameter if you do not want the error information. Return Value YES if the local item was removed successfully or NO if it was not. If NO is returned and errorOut is not nil, an NSError object describing the error is returned in that parameter. Discussion This method does not remove the item from the cloud. It removes only the local version. You can use this method to force iCloud to download a new version of the file or directory from the server. To delete a file permanently from the user’s iCloud storage, use the regular NSFileManager routines for deleting files and directories. Remember that deleting items from iCloud cannot be undone. Once deleted, the item is gone forever. Availability Available in iOS 5.0 and later. See Also – setUbiquitous:itemAtURL:destinationURL:error: (page 657) – removeItemAtURL:error: (page 653) Declared in NSFileManager.h NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 635fileAttributesAtPath:traverseLink: Returns a dictionary that describes the POSIX attributes of the file specified at a given. (Deprecated in iOS 2.0. Use attributesOfItemAtPath:error: (page 610) instead.) - (NSDictionary *)fileAttributesAtPath:(NSString *)path traverseLink:(BOOL)flag Parameters path A file path. flag If path is not a symbolic link, this parameter has no effect. If path is a symbolic link, then: ● If YES the attributes of the linked-to file are returned, or if the link points to a nonexistent file the method returns nil. ● If NO, the attributes of the symbolic link are returned. Return Value An NSDictionary object that describes the POSIX attributes of the file specified at path. The keys in the dictionary are described in “File Attribute Keys” (page 672). If there is no item at path, returns nil. Discussion This code example gets several attributes of a file and logs them. NSFileManager *fileManager = [[NSFileManager alloc] init]; NSString *path = @"/tmp/List"; NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES]; if (fileAttributes != nil) { NSNumber *fileSize; NSString *fileOwner; NSDate *fileModDate; if (fileSize = [fileAttributes objectForKey:NSFileSize]) { NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]); } if (fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName]) { NSLog(@"Owner: %@\n", fileOwner); } NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 636if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) { NSLog(@"Modification date: %@\n", fileModDate); } } else { NSLog(@"Path (%@) is invalid.", path); } [fileManager release]; As a convenience, NSDictionary provides a set of methods (declared as a category in NSFileManager.h) for quickly and efficiently obtaining attribute information from the returned dictionary: fileGroupOwnerAccountName (page 476), fileModificationDate (page 478), fileOwnerAccountName (page 479), filePosixPermissions (page 479), fileSize (page 480), fileSystemFileNumber (page 481), fileSystemNumber (page 481), and fileType (page 482). For example, you could rewrite the file modification statement in the code example above as: if (fileModDate = [fileAttributes fileModificationDate]) NSLog(@"Modification date: %@\n", fileModDate); Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use attributesOfItemAtPath:error: (page 610) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – attributesOfItemAtPath:error: (page 610) – setAttributes:ofItemAtPath:error: (page 656) Declared in NSFileManager.h fileExistsAtPath: Returns a Boolean value that indicates whether a file or directory exists at a specified path. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 637- (BOOL)fileExistsAtPath:(NSString *)path Parameters path The path of the file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath (page 1634), otherwise, this method returns NO. Return Value YES if a file at the specified path exists or NO if the file’s does not exist or its existence could not be determined. Discussion If the file at path is inaccessible to your application, perhaps because one or more parent directories are inaccessible, this method returns NO. If the final element in path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file at the link destination. Note Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions, File Operations, and Interprocess Communication” in Secure Coding Guide. Availability Available in iOS 2.0 and later. See Also – fileExistsAtPath:isDirectory: (page 638) Declared in NSFileManager.h fileExistsAtPath:isDirectory: Returns a Boolean value that indicates whether a file or directory exists at a specified path. - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory Parameters path The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath (page 1634), or this method will return NO. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 638isDirectory Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information. Return Value YES if a file at the specified path exists or NO if the file’s does not exist or its existence could not be determined. Discussion If the file at path is inaccessible to your application, perhaps because one or more parent directories are inaccessible, this method returns NO. If the final element in path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file at the link destination. If you need to further determine if path is a package, use the isFilePackageAtPath: method of NSWorkspace. This example gets an array that identifies the fonts in the user's fonts directory: NSArray *subpaths; BOOL isDir; NSArray *paths = NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES); if ([paths count] == 1) { NSFileManager *fileManager = [[NSFileManager alloc] init]; NSString *fontPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Fonts"]; if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) { subpaths = [fileManager subpathsAtPath:fontPath]; // ... [fileManager release]; NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 639Note Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions, File Operations, and Interprocess Communication” in Secure Coding Guide. Availability Available in iOS 2.0 and later. See Also – fileExistsAtPath: (page 637) Declared in NSFileManager.h fileSystemAttributesAtPath: Returns a dictionary that describes the attributes of the mounted file system on which a given path resides. (Deprecated in iOS 2.0. Use attributesOfFileSystemForPath:error: (page 609) instead.) - (NSDictionary *)fileSystemAttributesAtPath:(NSString *)path Parameters path Any pathname within the mounted file system. Return Value An NSDictionary object that describes the attributes of the mounted file system on which path resides. See “File-System Attribute Keys” (page 678) for a description of the keys available in the dictionary. Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use attributesOfFileSystemForPath:error: (page 609) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 640See Also – attributesOfFileSystemForPath:error: (page 609) – attributesOfItemAtPath:error: (page 610) – setAttributes:ofItemAtPath:error: (page 656) Declared in NSFileManager.h fileSystemRepresentationWithPath: Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system. - (const char *)fileSystemRepresentationWithPath:(NSString *)path Parameters path A string object containing a path to a file. This parameter must not be nil or contain the empty string. Return Value A C-string representation of path that properly encodes Unicode strings for use by the file system. Discussion Use this method if your code calls system routines that expect C-string path arguments. If you use the C string beyond the scope of the current autorelease pool, you must copy it. This method raises an exception if path is nil or contains the empty string. This method also throws an exception if the conversion of the string fails. Availability Available in iOS 2.0 and later. See Also – stringWithFileSystemRepresentation:length: (page 660) Declared in NSFileManager.h init Returns an initialized NSFileManager instance. - init NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 641Return Value An initialized NSFileManager instance. Discussion In Mac OS X v 10.4 and earlier sending the init message was undefined. In iOS and Mac OS X 10.5 and later you can use this method to create a specific file manager instance. You might do this in situations where you want to associate a delegate with the file manager to receive notifications about the status of file-related operations. isDeletableFileAtPath: Returns a Boolean value that indicates whether the invoking object appears able to delete a specified file. - (BOOL)isDeletableFileAtPath:(NSString *)path Parameters path A file path. Return Value YES if the current process has delete privileges for the file at path; otherwise NO if the process does not have delete privileges or the existence of the file could not be determined. Discussion For a directory or file to be deletable, the current process must either be able to write to the parent directory of path or it must have the same owner as the item at path. If path is a directory, every item contained in path must be deletable by the current process. If the file at path is inaccessible to your application, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method does not traverse symbolic links in the path. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 642Note Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions, File Operations, and Interprocess Communication” in Secure Coding Guide. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h isExecutableFileAtPath: Returns a Boolean value that indicates whether the operating system appears able to execute a specified file. - (BOOL)isExecutableFileAtPath:(NSString *)path Parameters path A file path. Return Value YES if the current process has execute privileges for the file at path; otherwise NO if the process does not have execute privileges or the existence of the file could not be determined. Discussion If the file at path is inaccessible to your application, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method traverses symbolic links in the path. This method also uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is executable. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 643Note Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions, File Operations, and Interprocess Communication” in Secure Coding Guide. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h isReadableFileAtPath: Returns a Boolean value that indicates whether the invoking object appears able to read a specified file. - (BOOL)isReadableFileAtPath:(NSString *)path Parameters path A file path. Return Value YES if the current process has read privileges for the file at path; otherwise NO if the process does not have read privileges or the existence of the file could not be determined. Discussion If the file at path is inaccessible to your application, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method traverses symbolic links in the path. This method also uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is readable. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 644Note Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions, File Operations, and Interprocess Communication” in Secure Coding Guide. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h isUbiquitousItemAtURL: Returns a Boolean indicating whether the item is targeted for storage in iCloud. - (BOOL)isUbiquitousItemAtURL:(NSURL *)url Parameters url Specify the URL for the file or directory whose status you want to check. Return Value YES if the item is targeted for iCloud storage or NO if it is not. This method also returns NO if no item exists at url. Discussion This method reflects only whether the item should be stored in iCloud because a call was made to the setUbiquitous:itemAtURL:destinationURL:error: (page 657) method with a value of YES for its flag parameter. This method does not reflect whether the file has actually been uploaded to any iCloud servers. To determine a file’s upload status, check the NSURLUbiquitousItemIsUploadedKey attribute of the corresponding NSURL object. Availability Available in iOS 5.0 and later. See Also – setUbiquitous:itemAtURL:destinationURL:error: (page 657) Declared in NSFileManager.h NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 645isWritableFileAtPath: Returns a Boolean value that indicates whether the invoking object appears able to write to a specified file. - (BOOL)isWritableFileAtPath:(NSString *)path Parameters path A file path. Return Value YES if the current process has write privileges for the file at path; otherwise NO if the process does not have write privileges or the existence of the file could not be determined. Discussion If the file at path is inaccessible to your application, perhaps because it does not have search privileges for one or more parent directories, this method returns NO. This method traverses symbolic links in the path. This method also uses the real user ID and group ID, as opposed to the effective user and group IDs, to determine if the file is writable. Note Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions, File Operations, and Interprocess Communication” in Secure Coding Guide. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h linkItemAtPath:toPath:error: Creates a hard link between the items at the specified paths. - (BOOL)linkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 646Parameters srcPath The path that specifies where you want to create the hard link. The value in this parameter must not be nil. dstPath The path that identifies the destination of the link. The value in this parameter must not be nil. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the hard link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at path. Discussion Use this method to create hard links between files in the current file system. If dstPath is a directory, this method creates a new directory at srcPath and then creates hard links for the items in that directory. If dstPath is (or contains) a symbolic link, the symbolic link is copied to the new location and not converted to a hard link. Prior to linking each item, the file manager asks its delegate if it should actually create the link. It does this by calling the fileManager:shouldLinkItemAtURL:toURL: (page 2020) method; if that method is not implemented it calls the fileManager:shouldLinkItemAtPath:toPath: (page 2019) method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager creates the hard link. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:linkingItemAtURL:toURL: (page 2026) or fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: (page 2024) method to determine how to proceed. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h linkItemAtURL:toURL:error: Creates a hard link between the items at the specified URLs. - (BOOL)linkItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 647Parameters srcURL The file URL that identifies the destination of the link. The URL in this parameter must not be a file reference URL; it must specify the actual path to the item. The value in this parameter must not be nil. dstURL The file URL that specifies where you want to create the hard link. The URL in this parameter must not be a file reference URL; it must specify the actual path to the item. The value in this parameter must not be nil. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the hard link was created or NO if an error occurred. This method also returns NO if a file, directory, or link already exists at path. Discussion Use this method to create hard links between files in the current file system. If dstURL is a directory, this method creates a new directory at srcURL and then creates hard links for the items in that directory. If dstURL is (or contains) a symbolic link, the symbolic link is copied and not converted to a hard link at srcURL. Prior to linking each item, the file manager asks its delegate if it should actually create the link. It does this by calling the fileManager:shouldLinkItemAtURL:toURL: (page 2020) method; if that method is not implemented it calls the fileManager:shouldLinkItemAtPath:toPath: (page 2019) method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager creates the hard link. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:linkingItemAtURL:toURL: (page 2026) or fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: (page 2024) method to determine how to proceed. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h mountedVolumeURLsIncludingResourceValuesForKeys:options: Returns an array of URLs that identify the mounted volumes available on the computer. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 648- (NSArray *)mountedVolumeURLsIncludingResourceValuesForKeys:(NSArray *)propertyKeys options:(NSVolumeEnumerationOptions)options Parameters propertyKeys An array of keys that identify the file properties that you want pre-fetched for each volume. For each returned URL, the values for these keys are cached in the corresponding NSURL objects. You may specify nil for this parameter. For a list of keys you can specify, see Common File System Resource Keys (page 1824). options Option flags for the enumeration. See “Mounted Volume Enumeration Options” (page 670). Return Value An array of NSURL objects identifying the mounted volumes. Discussion This call may block if I/O is required to determine values for the requested propertyKeys. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h moveItemAtPath:toPath:error: Moves the file or directory at the specified path to a new location synchronously. - (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error Parameters srcPath The path to the file or directory you want to move. This parameter must not be nil. dstPath The new path for the item in srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 649Return Value YES if the item was moved successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred. Discussion When moving items, the current process must have permission to read the item at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method moves the directory and all of its contents, including any hidden files. If an item with the same name already exists at dstPath, this method aborts the move attempt and returns an appropriate error. If the last component of srcPath is a symbolic link, only the link is moved to the new path; the item pointed to by the link remains at its current location. Prior to moving the item, the file manager asks its delegate if it should actually move it. It does this by calling the fileManager:shouldMoveItemAtURL:toURL: (page 2022) method; if that method is not implemented it calls the fileManager:shouldMoveItemAtPath:toPath: (page 2021) method instead. If the item being moved is a directory, the file manager notifies the delegate only for the directory itself and not for any of its contents. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager moves the file. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:movingItemAtURL:toURL: (page 2028) or fileManager:shouldProceedAfterError:movingItemAtPath:toPath: (page 2027) method to determine how to proceed. If the source and destination of the move operation are not on the same volume, this method copies the item first and then removes it from its current location. This behavior may trigger additional delegate notifications related to copying and removing individual items. Availability Available in iOS 2.0 and later. See Also – moveItemAtURL:toURL:error: (page 650) – copyItemAtPath:toPath:error: (page 617) – removeItemAtPath:error: (page 652) Declared in NSFileManager.h moveItemAtURL:toURL:error: Moves the file or directory at the specified URL to a new location synchronously. - (BOOL)moveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 650Parameters srcURL The file URL that identifies the file or directory you want to move. The URL in this parameter must not be a file reference URL. This parameter must not be nil. dstURL The new location for the item in srcURL. The URL in this parameter must not be a file reference URL and must include the name of the file or directory in its new location. This parameter must not be nil. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the item was moved successfully or the file manager’s delegate aborted the operation deliberately. Returns NO if an error occurred. Discussion When moving items, the current process must have permission to read the item at srcURL and write the parent directory of dstURL. If the item at srcURL is a directory, this method moves the directory and all of its contents, including any hidden files. If an item with the same name already exists at dstURL, this method aborts the move attempt and returns an appropriate error. If the last component of srcURL is a symbolic link, only the link is moved to the new path; the item pointed to by the link remains at its current location. Prior to moving the item, the file manager asks its delegate if it should actually move it. It does this by calling the fileManager:shouldMoveItemAtURL:toURL: (page 2022) method; if that method is not implemented it calls the fileManager:shouldMoveItemAtPath:toPath: (page 2021) method instead. If the item being moved is a directory, the file manager notifies the delegate only for the directory itself and not for any of its contents. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager moves the file. If there is an error moving one out of several items, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:movingItemAtURL:toURL: (page 2028) or fileManager:shouldProceedAfterError:movingItemAtPath:toPath: (page 2027) method to determine how to proceed. If the source and destination of the move operation are not on the same volume, this method copies the item first and then removes it from its current location. This behavior may trigger additional delegate notifications related to copying and removing individual items. Availability Available in iOS 4.0 and later. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 651See Also – moveItemAtPath:toPath:error: (page 649) – copyItemAtURL:toURL:error: (page 618) – removeItemAtURL:error: (page 653) Declared in NSFileManager.h pathContentOfSymbolicLinkAtPath: Returns the path of the directory or file that a symbolic link at a given path refers to. (Deprecated in iOS 2.0. Use destinationOfSymbolicLinkAtPath:error: (page 628) instead.) - (NSString *)pathContentOfSymbolicLinkAtPath:(NSString *)path Parameters path The path of a symbolic link. Return Value The path of the directory or file to which the symbolic link path refers, or nil upon failure. If the symbolic link is specified as a relative path, that relative path is returned. Special Considerations Because this method does not return error information, it has been deprecated as of Mac OS X v10.5. Use destinationOfSymbolicLinkAtPath:error: (page 628) instead. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – destinationOfSymbolicLinkAtPath:error: (page 628) – createSymbolicLinkAtPath:withDestinationPath:error: (page 625) Declared in NSFileManager.h removeItemAtPath:error: Removes the file or directory at the specified path. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 652- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error Parameters path A path string indicating the file or directory to remove. If the path specifies a directory, the contents of that directory are recursively removed. You may specify nil for this parameter. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the item was removed successfully or if path was nil. Returns NO if an error occurred. If the delegate aborts the operation for a file, this method returns YES. However, if the delegate aborts the operation for a directory, this method returns NO. Discussion Prior to removing each item, the file manager asks its delegate if it should actually do so. It does this by calling the fileManager:shouldRemoveItemAtURL: (page 2031) method; if that method is not implemented (or the process is running in Mac OS X 10.5 or earlier) it calls the fileManager:shouldRemoveItemAtPath: (page 2031) method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager proceeds to remove the file or directory. If there is an error removing an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:removingItemAtURL: (page 2030) or fileManager:shouldProceedAfterError:removingItemAtPath: (page 2029) method to determine how to proceed. Availability Available in iOS 2.0 and later. Related Sample Code AQOfflineRenderTest iPhoneExtAudioFileConvertTest Declared in NSFileManager.h removeItemAtURL:error: Removes the file or directory at the specified URL. - (BOOL)removeItemAtURL:(NSURL *)URL error:(NSError **)error NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 653Parameters URL A file URL specifying the file or directory to remove. If the URL specifies a directory, the contents of that directory are recursively removed. You may specify nil for this parameter. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the item was removed successfully or if URL was nil. Returns NO if an error occurred. If the delegate aborts the operation for a file, this method returns YES. However, if the delegate aborts the operation for a directory, this method returns NO. Discussion Prior to removing each item, the file manager asks its delegate if it should actually do so. It does this by calling the fileManager:shouldRemoveItemAtURL: (page 2031) method; if that method is not implemented (or the process is running in Mac OS X 10.5 or earlier) it calls the fileManager:shouldRemoveItemAtPath: (page 2031) method instead. If the delegate method returns YES, or if the delegate does not implement the appropriate methods, the file manager proceeds to remove the file or directory. If there is an error removing an item, the file manager may also call the delegate’s fileManager:shouldProceedAfterError:removingItemAtURL: (page 2030) or fileManager:shouldProceedAfterError:removingItemAtPath: (page 2029) method to determine how to proceed. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: Replaces the contents of the item at the specified URL in a manner that insures no data loss occurs. - (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL backupItemName:(NSString *)backupItemName options:(NSFileManagerItemReplacementOptions)options resultingItemURL:(NSURL **)resultingURL error:(NSError **)error NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 654Parameters originalItemURL The item whose contents you want to replace. newItemURL The item containing the new content for originalItemURL. It is recommended that you put this item in a temporary directory as provided by the OS. If a temporary directory is not available, put this item in a uniquely named directory that is in the same directory as the original item. backupItemName Optional. If provided, this name is used to create a backup of the original item. The backup is placed in the same directory as the original item. If an error occurs during the creation of the backup item, the operation will fail. If there is already an item with the same name as the backup item, that item will be removed. The backup item will be removed in the event of success unless the NSFileManagerItemReplacementWithoutDeletingBackupItem (page 672) option is provided in options. options Specifies the options to use during the replacement. Typically, you pass 0 for this parameter, which uses only the metadata from the new item. You can also combine the options described in “NSFileManagerItemReplacementOptions” (page 671) using the C-bitwise OR operator. resultingURL On input, a pointer for a URL object. When the item is replaced, this pointer is set to the URL of the new item. If no new file system object is required, the URL object in this parameter may be the same passed to the originalItemURL parameter. However, if a new file system object is required, the URL object may be different. For example, replacing an RTF document with an RTFD document requires the creation of a new file. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if the replacement was successful or NO if an error occurred. Discussion By default, the creation date, permissions, Finder label and color, and Spotlight comments of the original item will be preserved on the resulting item. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 655If an error occurs and the original item is not in the original location or a temporary location, the returned error object contains a user info dictionary with the NSFileOriginalItemLocationKey key. The value assigned to that key is an NSURL object with the location of the item. The error code is one of the file-related errors described in NSError Codes (page 2274). Availability Available in iOS 4.0 and later. Declared in NSFileManager.h setAttributes:ofItemAtPath:error: Sets the attributes of the specified file or directory. - (BOOL)setAttributes:(NSDictionary *)attributes ofItemAtPath:(NSString *)path error:(NSError **)error Parameters attributes A dictionary containing as keys the attributes to set for path and as values the corresponding value for the attribute. You can set the following attributes: NSFileBusy (page 673), NSFileCreationDate (page 673), NSFileExtensionHidden (page 674), NSFileGroupOwnerAccountID (page 674), NSFileGroupOwnerAccountName (page 674), NSFileHFSCreatorCode (page 674), NSFileHFSTypeCode (page 675), NSFileImmutable (page 675), NSFileModificationDate (page 675), NSFileOwnerAccountID (page 675), NSFileOwnerAccountName (page 674), NSFilePosixPermissions (page 675). You can change single attributes or any combination of attributes; you need not specify keys for all attributes. path The path of a file or directory. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value YES if all changes succeed. If any change fails, returns NO, but it is undefined whether any changes actually occurred. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 656Discussion As in the POSIX standard, the application either must own the file or directory or must be running as superuser for attribute changes to take effect. The method attempts to make all changes specified in attributes and ignores any rejection of an attempted modification. If the last component of the path is a symbolic link it is traversed. The NSFilePosixPermissions (page 675) value must be initialized with the code representing the POSIX file-permissions bit pattern. NSFileHFSCreatorCode (page 674) and NSFileHFSTypeCode (page 675) will only be heeded when path specifies a file. Availability Available in iOS 2.0 and later. See Also – attributesOfItemAtPath:error: (page 610) Declared in NSFileManager.h setDelegate: Sets the delegate for the receiver. - (void)setDelegate:(id)delegate Parameters delegate The delegate for the receiver. The delegate must implement the NSFileManagerDelegate protocol. Discussion It is recommended that you assign a delegate only to file manager objects that you create explicitly using the alloc/init convention. Availability Available in iOS 2.0 and later. Declared in NSFileManager.h setUbiquitous:itemAtURL:destinationURL:error: Sets whether the item at the specified URL should be stored in the cloud. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 657- (BOOL)setUbiquitous:(BOOL)flag itemAtURL:(NSURL *)url destinationURL:(NSURL *)destinationURL error:(NSError **)errorOut Parameters flag Specify YES to move the item to iCloud or NO to remove it from iCloud (if it is there currently). url Specify the URL of the item (file or directory) that you want to store in iCloud. destinationURL Specify the location in iCloud at which to store the file or directory. This URL must be constructed from a URL returned by the URLForUbiquityContainerIdentifier: (page 665) method, which you use to retrieve the desired iCloud container directory. The URL you specify may contain additional subdirectories so that you can organize your files hierarchically in iCloud. However, you are responsible for creating those intermediate subdirectories (using the NSFileManager class) in your iCloud container directory. errorOut On input, a pointer to variable for an NSError object. If an error occurs, this pointer is set to an NSError object containing information about the error. You may specify nil for this parameter if you do not want the error information. Return Value YES if the item’s status was updated successfully or NO if an error occurred. If this method returns NO and you specified a value for the errorOut parameter, this method returns an error object in the provided pointer. Discussion Use this method to move a file from its current location to iCloud. For files located in an application’s sandbox, this involves physically removing the file from the sandbox directory. (The system extends your application’s sandbox privileges to give it access to files it moves to iCloud.) You can also use this method to move files out of iCloud and back into a local directory. Your application must have an active file presenter object configured to monitor the specified file or directory before calling this method. When you specify YES for the flag parameter, this method attempts to move the file or directory to the cloud and returns YES if it is successful. This method also notifies your file presenter of the new location of the file so that your application can continue to operate on it. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 658Important Do not call this method from your application’s main thread. This method performs a coordinated write operation on the file you specify, and calling this method from the main thread can trigger a deadlock with the file presenter you have monitoring the file. Instead, use a dispatch queue (other than the main thread queue) to perform the method call on a secondary thread. You can always message your main thread after the call finishes to update the rest of your application’s data structures. Availability Available in iOS 5.0 and later. See Also – startDownloadingUbiquitousItemAtURL:error: (page 659) – isUbiquitousItemAtURL: (page 645) – URLForPublishingUbiquitousItemAtURL:expirationDate:error: (page 664) Declared in NSFileManager.h startDownloadingUbiquitousItemAtURL:error: Starts downloading (if necessary) the specified item to the local system. - (BOOL)startDownloadingUbiquitousItemAtURL:(NSURL *)url error:(NSError **)errorOut Parameters url Specify the URL for the file or directory in the cloud that you want to download. errorOut On input, a pointer to variable for an NSError object. If an error occurs, this pointer is set to an NSError object containing information about the error. You may specify nil for this parameter if you do not want the error information. Return Value YES if the download started successfully or was not necessary, otherwise NO. If NO is returned and errorOut is not nil, an NSError object describing the error is returned in that parameter. Discussion If a cloud-based file or directory has not been downloaded yet, calling this method starts the download process. If the item exists locally, calling this method synchronizes the local copy with the version in the cloud. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 659For a given URL, you can determine if a file is downloaded by getting the value of the NSMetadataUbiquitousItemIsDownloadedKey (page 895) key. You can also use related keys to determine the current progress in downloading the file. Availability Available in iOS 5.0 and later. See Also – setUbiquitous:itemAtURL:destinationURL:error: (page 657) Declared in NSFileManager.h stringWithFileSystemRepresentation:length: Returns an NSString object whose contents are derived from the specified C-string path. - (NSString *)stringWithFileSystemRepresentation:(const char *)string length:(NSUInteger)len Parameters string A C string representation of a pathname. len The number of characters in string. Return Value An NSString object converted from the C-string representation string with length len of a pathname in the current file system. Discussion Use this method if your code receives paths as C strings from system routines. Availability Available in iOS 2.0 and later. See Also – fileSystemRepresentationWithPath: (page 641) Declared in NSFileManager.h NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 660subpathsAtPath: Returns an array of strings identifying the paths for all items in the specified directory. - (NSArray *)subpathsAtPath:(NSString *)path Parameters path The path of the directory to list. Return Value An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file. Discussion This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion. This method reveals every element of the subtree at path, including the contents of file packages (such as applications, nib files, and RTFD files). This code fragment gets the contents of /System/Library/Fonts after verifying that the directory exists: BOOL isDir=NO; NSArray *subpaths; NSString *fontPath = @"/System/Library/Fonts"; NSFileManager *fileManager = [[NSFileManager alloc] init]; if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) subpaths = [fileManager subpathsAtPath:fontPath]; [fileManager release]; Special Considerations On Mac OS X v10.5 and later, use subpathsOfDirectoryAtPath:error: (page 662) instead. Availability Available in iOS 2.0 and later. See Also – subpathsOfDirectoryAtPath:error: (page 662) – contentsOfDirectoryAtPath:error: (page 615) – enumeratorAtPath: (page 630) NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 661Declared in NSFileManager.h subpathsOfDirectoryAtPath:error: Performsadeepenumerationofthespecifieddirectoryandreturnsthepathsofallofthecontainedsubdirectories. - (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error Parameters path The path of the directory to list. error If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file. Discussion This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion. Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time. Availability Available in iOS 2.0 and later. See Also – enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: (page 632) – enumeratorAtPath: (page 630) – contentsOfDirectoryAtPath:error: (page 615) Declared in NSFileManager.h NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 662URLForDirectory:inDomain:appropriateForURL:create:error: Locates and optionally creates the specified common directory in a domain. - (NSURL *)URLForDirectory:(NSSearchPathDirectory)directory inDomain:(NSSearchPathDomainMask)domain appropriateForURL:(NSURL *)url create:(BOOL)shouldCreate error:(NSError **)error Parameters directory The search path directory. The supported values are described in NSSearchPathDirectory (page 2270). domain The file system domain to search. The value for this parameter is one of the constants described in NSSearchPathDomainMask (page 2273). You should specify only one domain for your search and you may not specify the NSAllDomainsMask constant for this parameter. url The name of a directory inside of which you want to create a unique temporary directory for autosaving documents or some other use. This parameter is ignored unless the directory parameter contains the value NSItemReplacementDirectory and the domain parameter contains the value NSUserDomainMask. When creating a temporary directory, the shouldCreate parameter is ignored and the directory is always created. shouldCreate Specify YES if you want the directory to be created if it does not exist. error On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information. Return Value The NSURL for the requested directory or nil if an error occurred. Discussion You typically use this method to locate one of the standard system directories, such as the Documents, Application Support or Caches directories. You can also use this method to create a new temporary directory for storing things like autosave files; to do so, specify NSItemReplacementDirectory for the directory parameter, NSUserDomainMask for the domain parameter, and a valid parent directory for the url parameter. After locating (or creating) the desired directory, this method returns the URL for that directory. If more than one appropriate directory exists in the specified domain, this method returns only the first one it finds. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 663Passing a directory and domain pair that makes no sense (for example NSDesktopDirectory and NSNetworkDomainMask) raises an exception. Availability Available in iOS 4.0 and later. See Also NSSearchPathForDirectoriesInDomains (page 2228) Declared in NSFileManager.h URLForPublishingUbiquitousItemAtURL:expirationDate:error: Returns a URL that can be emailed to users to allow them to download a copy of a cloud-based item. - (NSURL *)URLForPublishingUbiquitousItemAtURL:(NSURL *)url expirationDate:(NSDate **)outDate error:(NSError **)error Parameters url Specify the URL of the item in the cloud that you want to share. The URL must be prefixed with the base URL returned from the URLForUbiquityContainerIdentifier: (page 665) method that corresponds to the item’s location. outDate On input, a pointer to a variable for a date object. On output, this parameter contains the date after which the item is no longer available at the returned URL. You may specify nil for this parameter if you are not interested in the date. error On input, a pointer to variable for an NSError object. If an error occurs, this pointer is set to an NSError object containing information about the error. You may specify nil for this parameter if you do not want the error information. Return Value A URL with which users can download a copy of the item at url. Returns nil if the URL could not be created for any reason. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 664Discussion This method creates a snapshot of the specified file and places that copy in a temporary iCloud location where it can be accessed by other users using the returned URL. The snapshot reflects the contents of the file at the time the URL was generated and is not updated when subsequent changes are made to the original file in the user’s iCloud storage. The snapshot file remains available at the specified URL until the date specified in the outDate parameter, after which it is automatically deleted. Your application must have access to the network for this call to succeed. Availability Available in iOS 5.0 and later. See Also – URLForUbiquityContainerIdentifier: (page 665) Declared in NSFileManager.h URLForUbiquityContainerIdentifier: Returns the iCloud directory associated with the specified container ID. - (NSURL *)URLForUbiquityContainerIdentifier:(NSString *)containerID Parameters containerID Specify the container ID of the cloud-based storage container. The string you specify must not contain wildcards and must be of the form ., where is your development team ID and describes the bundle identifier of the container you want to access. The container identifiers for your application must be declared in the com.apple.developer.ubiquity-container-identifiers entitlement. If you specify nil, this method returns the first container listed in the com.apple.developer.ubiquity-container-identifiers entitlement. Return Value A URL pointing to the specified container directory or nil if the container could not be located or if iCloud storage is unavailable for the current user or device. NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 665Discussion You can use the URL returned by this method to build paths to files and directories in the user’s iCloud storage. Each application that syncs documents to the cloud must have at least one associated container directory in which to put those files. This container directory can be unique to the application or shared by multiple applications. You use this method to retrieve the URL for that container directory. In addition to writing to its own container directory, an application can write to any container directory for which it has the appropriate permission. Each additional container directory should be listed as an additional value in the com.apple.developer.ubiquity-container-identifiers entitlement. Note The development team ID that precedes each container ID string is the unique identifier associated with your development team. You can find this string in the Member Center of the Apple Developer website (http://developer.apple.com/membercenter). From the Member Center home page, select the Your Account tab and then select Organization Profile from the column on the left of that tab. Your team’s identifier is in the Company/Organization ID field. The first time you call this method for a given container directory, iOS extends your application sandbox to include that container directory. Thus, it is important that you call this method at least once before trying to search for files in iCloud. And if your application accesses multiple container directories, you should call the method once for each directory. Availability Available in iOS 5.0 and later. See Also – URLForPublishingUbiquitousItemAtURL:expirationDate:error: (page 664) Declared in NSFileManager.h URLsForDirectory:inDomains: Returns an array of URLs for the specified common directory in the requested domains. - (NSArray *)URLsForDirectory:(NSSearchPathDirectory)directory inDomains:(NSSearchPathDomainMask)domainMask Parameters directory The search path directory. The supported values are described in NSSearchPathDirectory (page 2270). NSFileManager Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 666domainMask The file system domain to search. The value for this parameter is one or more of the constants described in NSSearchPathDomainMask (page 2273). Return Value An array of NSURL objects identifying the requested directories. The directories are ordered according to the order of the domain mask constants, with items in the user domain first and items in the system domain last. Discussion This method is intended to locate known and common directories in the system. For example, setting the directory to NSApplicationDirectory, will return the Applications directories in the requested domain. There are a number of common directories available in the NSSearchPathDirectory (page 2270), including: NSDesktopDirectory, NSApplicationSupportDirectory, and many more. Availability Available in iOS 4.0 and later. Declared in NSFileManager.h Delegate Methods fileManager:shouldProceedAfterError: An NSFileManager object sends this message to its handler for each error it encounters when copying, moving, removing, or linking files or directories. (Deprecated in iOS 2.0. See delegate methods for copy, move, remove, and link methods.) - (BOOL)fileManager:(NSFileManager *)manager shouldProceedAfterError:(NSDictionary *)errorInfo Parameters manager The file manager that sent this message. NSFileManager Class Reference Delegate Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 667errorInfo A dictionary that contains two or three pieces of information (all NSString objects) related to the error: ValueKey The path related to the error (usually the source path)@"Path" A description of the error@"Error" The destination path (not all errors)@"ToPath" Return Value YES if the operation (which is often continuous within a loop) should proceed, otherwise NO. Discussion An NSFileManager object, manager, sends this message for each error it encounters when copying, moving, removing, or linking files or directories. The return value is passed back to the invoker of copyPath:toPath:handler:, movePath:toPath:handler:, removeFileAtPath:handler:, or linkPath:toPath:handler:. If an error occurs and your handler has not implemented this method, the invoking method automatically returns NO. The following implementation of fileManager:shouldProceedAfterError: displays the error string in an alert dialog and leaves it to the user whether to proceed or stop: -(BOOL)fileManager:(NSFileManager *)manager shouldProceedAfterError:(NSDictionary *)errorInfo { int result; result = NSRunAlertPanel(@"Gumby App", @"File operation error: %@ with file: %@", @"Proceed", @"Stop", NULL, [errorInfo objectForKey:@"Error"], [errorInfo objectForKey:@"Path"]); if (result == NSAlertDefaultReturn) return YES; else return NO; } NSFileManager Class Reference Delegate Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 668Special Considerations The copyPath:toPath:handler:, movePath:toPath:handler:, removeFileAtPath:handler:, and linkPath:toPath:handler: methods have all been deprecated as of Mac OS X v10.5. Instead, you can call the setDelegate: (page 657) method to specify a delegate that can receive a variety of messages, including messages that replace those described in this section. See the descriptions of the delegate methods in this document for details. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. See Also – fileManager:willProcessPath: (page 669) – setDelegate: (page 657) Declared in NSFileManager.h fileManager:willProcessPath: An NSFileManager object sends this message to a handler immediately before attempting to move, copy, rename, or delete, or before attempting to link to a given path. (Deprecated in iOS 2.0. See delegate methods for copy, move, link, and remove methods.) - (void)fileManager:(NSFileManager *)manager willProcessPath:(NSString *)path Parameters manager The NSFileManager object that sent this message. path The path or a file or directory that manager is about to attempt to move, copy, rename, delete, or link to. Discussion You can implement this method in your handler to monitor file operations. NSFileManager Class Reference Delegate Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 669Special Considerations The copyPath:toPath:handler:, movePath:toPath:handler:, removeFileAtPath:handler:, and linkPath:toPath:handler: methods have all been deprecated as of Mac OS X v10.5. Instead, you can call the setDelegate: (page 657) method to specify a delegate that can receive a variety of messages, including messages that replace those described in this section. See the descriptions of the delegate methods in this document for details. Availability Available in iOS 2.0 and later. Deprecated in iOS 2.0. Declared in NSFileManager.h Constants Mounted Volume Enumeration Options Options for enumerating mounted volumes with the mountedVolumeURLsIncludingResourceValuesForKeys:options: (page 648) method. enum { NSVolumeEnumerationSkipHiddenVolumes = 1L << 1, NSVolumeEnumerationProduceFileReferenceURLs = 1L << 2 }; typedef NSUInteger NSVolumeEnumerationOptions; Constants NSVolumeEnumerationSkipHiddenVolumes The enumeration skips hidden volumes. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSVolumeEnumerationProduceFileReferenceURLs The enumeration produces file reference URLs rather than path-based URLs. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 670Directory Enumeration Options Options for enumerating the contents of directories with the contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: (page 616) method. enum { NSDirectoryEnumerationSkipsSubdirectoryDescendants = 1L << 0, NSDirectoryEnumerationSkipsPackageDescendants = 1L << 1, NSDirectoryEnumerationSkipsHiddenFiles = 1L << 2 }; typedef NSUInteger NSDirectoryEnumerationOptions; Constants NSDirectoryEnumerationSkipsSubdirectoryDescendants Perform a shallow enumeration; do not descend into directories. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSDirectoryEnumerationSkipsPackageDescendants Do not descend into packages. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSDirectoryEnumerationSkipsHiddenFiles Do not enumerate hidden files. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSFileManagerItemReplacementOptions The constants specify the replacement behavior in NSFileManagerItemReplacementWithoutDeletingBackupItem (page 672). NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 671enum { NSFileManagerItemReplacementUsingNewMetadataOnly = 1UL << 0, NSFileManagerItemReplacementWithoutDeletingBackupItem = 1UL << 1 }; typedef NSUInteger NSFileManagerItemReplacementOptions; Constants NSFileManagerItemReplacementUsingNewMetadataOnly Causes NSFileManagerItemReplacementWithoutDeletingBackupItem (page 672) to use metadata from the new item only and not to attempt to preserve metadata from the original item. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSFileManagerItemReplacementWithoutDeletingBackupItem Causes NSFileManagerItemReplacementWithoutDeletingBackupItem (page 672) to leave the backup item in place after a successful replacement. The default behavior is to remove the item. Available in iOS 4.0 and later. Declared in NSFileManager.h. File Attribute Keys These keys access file attribute values contained in NSDictionary objects used by setAttributes:ofItemAtPath:error: (page 656), attributesOfItemAtPath:error: (page 610), createDirectoryAtPath:withIntermediateDirectories:attributes:error: (page 621), and createFileAtPath:contents:attributes: (page 623). NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 672NSString * const NSFileType; NSString * const NSFileSize; NSString * const NSFileModificationDate; NSString * const NSFileReferenceCount; NSString * const NSFileDeviceIdentifier; NSString * const NSFileOwnerAccountName; NSString * const NSFileGroupOwnerAccountName; NSString * const NSFilePosixPermissions; NSString * const NSFileSystemNumber; NSString * const NSFileSystemFileNumber; NSString * const NSFileExtensionHidden; NSString * const NSFileHFSCreatorCode; NSString * const NSFileHFSTypeCode; NSString * const NSFileImmutable; NSString * const NSFileAppendOnly; NSString * const NSFileCreationDate; NSString * const NSFileOwnerAccountID; NSString * const NSFileGroupOwnerAccountID; NSString * const NSFileBusy; NSString* const NSFileProtectionKey; Constants NSFileAppendOnly The key in a file attribute dictionary whose value indicates whether the file is read-only. The corresponding value is an NSNumber object containing a Boolean value. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileBusy The key in a file attribute dictionary whose value indicates whether the file is busy. The corresponding value is an NSNumber object containing a Boolean value. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileCreationDate The key in a file attribute dictionary whose value indicates the file's creation date. The corresponding value is an NSDate object. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 673NSFileOwnerAccountName The key in a file attribute dictionary whose value indicates the name of the file's owner. The corresponding value is an NSString object. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileGroupOwnerAccountName The key in a file attribute dictionary whose value indicates the group name of the file's owner. The corresponding value is an NSString object. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileDeviceIdentifier The key in a file attribute dictionary whose value indicates the identifier for the device on which the file resides. The corresponding value is an NSNumber object containing an unsigned long. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileExtensionHidden The key in a file attribute dictionary whose value indicates whether the file's extension is hidden. The corresponding value is an NSNumber object containing a Boolean value. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileGroupOwnerAccountID The key in a file attribute dictionary whose value indicates the file's group ID. The corresponding value is an NSNumber object containing an unsigned long. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileHFSCreatorCode The key in a file attribute dictionary whose value indicates the file's HFS creator code. The corresponding value is an NSNumber object containing an unsigned long. See “HFS File Types” for possible values. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 674NSFileHFSTypeCode The key in a file attribute dictionary whose value indicates the file's HFS type code. The corresponding value is an NSNumber object containing an unsigned long. See “HFS File Types” for possible values. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileImmutable The key in a file attribute dictionary whose value indicates whether the file is mutable. The corresponding value is an NSNumber object containing a Boolean value. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileModificationDate The key in a file attribute dictionary whose value indicates the file's last modified date. The corresponding value is an NSDate object. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileOwnerAccountID The key in a file attribute dictionary whose value indicates the file's owner's account ID. The corresponding value is an NSNumber object containing an unsigned long. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFilePosixPermissions The key in a file attribute dictionary whose value indicates the file's Posix permissions. The corresponding value is an NSNumber object. Use the shortValue (page 1123) method to retrieve the integer value for the permissions. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileReferenceCount The key in a file attribute dictionary whose value indicates the file's reference count. The corresponding value is an NSNumber object containing an unsigned long. The number specifies the number of hard links to a file. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 675NSFileSize The key in a file attribute dictionary whose value indicates the file's size in bytes. The corresponding value is an NSNumber object containing an unsigned long long. Important If the file has a resource fork, the returned value does not include the size of the resource fork. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileSystemFileNumber The key in a file attribute dictionary whose value indicates the file's filesystem file number. The corresponding value is an NSNumber object containing an unsigned long. The value corresponds to the value of st_ino, as returned by stat(2). Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileType The key in a file attribute dictionary whose value indicates the file's type. The corresponding value is an NSString object (see “NSFileType Attribute Values” (page 676) for possible values). Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileProtectionKey The extended attribute key that identifies the protection level for this file. The corresponding value is an NSString value. For a list of possible values, see “File Protection Values” (page 679). Available in iOS 4.0 and later. Declared in NSFileManager.h. Discussion NSFileDeviceIdentifier (page 674) is used to access the identifier of a remote device. Declared in NSFileManager.h NSFileType Attribute Values Thesestringsarethepossiblevaluesforthe NSFileType (page 676) attributekeycontainedinthedictionaryobject returned by attributesOfItemAtPath:error: (page 610). NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 676NSString * const NSFileTypeDirectory; NSString * const NSFileTypeRegular; NSString * const NSFileTypeSymbolicLink; NSString * const NSFileTypeSocket; NSString * const NSFileTypeCharacterSpecial; NSString * const NSFileTypeBlockSpecial; NSString * const NSFileTypeUnknown; Constants NSFileTypeDirectory Directory Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileTypeRegular Regular file Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileTypeSymbolicLink Symbolic link Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileTypeSocket Socket Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileTypeCharacterSpecial Character special file Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileTypeBlockSpecial Block special file Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileTypeUnknown Unknown Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 677File-System Attribute Keys Keys to access the file attribute values contained in the dictionary object returned from the attributesOfFileSystemForPath:error: (page 609) method. extern NSString *NSFileSystemSize; extern NSString *NSFileSystemFreeSize; extern NSString *NSFileSystemNodes; extern NSString *NSFileSystemFreeNodes; extern NSString *NSFileSystemNumber; Constants NSFileSystemSize The key in a file system attribute dictionary whose value indicates the size of the file system. The corresponding value is an NSNumber object that specifies the size of the file system in bytes. The value is determined by statfs(). Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileSystemFreeSize The key in a file system attribute dictionary whose value indicates the amount of free space on the file system. The corresponding value is an NSNumber object that specifies the amount of free space on the file system in bytes. The value is determined by statfs(). Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileSystemNodes The key in a file system attribute dictionary whose value indicates the number of nodes in the file system. The corresponding value is an NSNumber object that specifies the number of nodes in the file system. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileSystemFreeNodes The key in a file system attribute dictionary dictionary whose value indicates the number of free nodes in the file system. The corresponding value is an NSNumber object that specifies the number of free nodes in the file system. Available in iOS 2.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 678NSFileSystemNumber The key in a file system attribute dictionary dictionary whose value indicates the filesystem number of the file system. The corresponding value is an NSNumber object that specifies the filesystem number of the file system. The value corresponds to the value of st_dev, as returned by stat(2). Available in iOS 2.0 and later. Declared in NSFileManager.h. File Protection Values Specifies the values that can be associated with the NSFileProtectionKey (page 676) key. extern NSString* const NSFileProtectionNone; extern NSString* const NSFileProtectionComplete; extern NSString* const NSFileProtectionCompleteUnlessOpen; extern NSString* const NSFileProtectionCompleteUntilFirstUserAuthentication; Constants NSFileProtectionNone The file has no special protections associated with it. It can be read from or written to at any time. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSFileProtectionComplete The file is stored in an encrypted format on disk and cannot be read from or written to while the device is locked or booting. Available in iOS 4.0 and later. Declared in NSFileManager.h. NSFileProtectionCompleteUnlessOpen The file is stored in an encrypted format on disk and must be opened while the device is unlocked. Once open, your file may continue to access the file normally, even if the user locks the device. Available in iOS 5.0 and later. Declared in NSFileManager.h. NSFileProtectionCompleteUntilFirstUserAuthentication The file is stored in an encrypted format on disk and cannot be accessed until after the device has booted. After the user unlocks the device for the first time, your application can access the file and continue to access it even if the user subsequently locks the device. Available in iOS 5.0 and later. Declared in NSFileManager.h. NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 679Resource Fork Support Specifies the version of the Foundation framework in which NSFileManager first supported resource forks. #define NSFoundationVersionWithFileManagerResourceForkSupport 412 Constants NSFoundationVersionWithFileManagerResourceForkSupport The version of the Foundation framework in which NSFileManager first supported resource forks. Available in iOS 2.0 and later. Declared in NSFileManager.h. Declared in NSFileManager.h NSFileManager Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 680Inherits from NSObject Conforms to NSCoding NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 4.0 and later. Declared in Foundation/NSFileWrapper.h Companion guide Application File Management Overview The NSFileWrapper class provides access to the attributes and contents of file-system nodes. A file-system node is a file, directory, or symbolic link. Instances of this class are known as file wrappers. File wrappers represent a file-system node as an object that can be displayed as an image (and possibly edited in place), saved to the file system, or transmitted to another application. There are three types of file wrappers: ● Regular-file file wrapper: Represents a regular file. ● Directory file wrapper: Represents a directory. ● Symbolic-link file wrapper: Represents a symbolic link. A file wrapper has these attributes: ● Filename. Name of the file-system node the file wrapper represents. ● file-system attributes. See NSFileManager Class Reference for information on the contents of the attributes dictionary. ● Regular-file contents. Applicable only to regular-file file wrappers. ● File wrappers. Applicable only to directory file wrappers. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 681 NSFileWrapper Class Reference ● Destination node. Applicable only to symbolic-link file wrappers. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) Tasks Creating File Wrappers This class has several designated initializers. – initWithURL:options:error: (page 695) Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the URL. – initWithPath: (page 694) Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the path. (Deprecated. Use initWithURL:options:error: (page 695) instead.) – initDirectoryWithFileWrappers: (page 690) Initializes the receiver as a directory file wrapper, with a given file-wrapper list. – initRegularFileWithContents: (page 691) Initializes the receiver as a regular-file file wrapper. – initSymbolicLinkWithDestinationURL: (page 693) Initializes the receiver as a symbolic-link file wrapper that links to a specified file. – initWithSerializedRepresentation: (page 694) Initializes the receiver as a regular-file file wrapper from given serialized data. – initSymbolicLinkWithDestination: (page 692) Available in iOS 4.0 through iOS 4.3 Initializes the receiver as a symbolic-link file wrapper. (Deprecated. Use initSymbolicLinkWithDestinationURL: (page 693) instead.) NSFileWrapper Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 682Querying File Wrappers – isRegularFile (page 697) Indicates whether the receiver is a regular-file file wrapper. – isDirectory (page 696) Indicates whether the receiver is a directory file wrapper. – isSymbolicLink (page 697) Indicates whether the receiver is a symbolic-link file wrapper. Accessing File-Wrapper Information – fileWrappers (page 690) Returns the file wrappers contained by a directory file wrapper. – addFileWrapper: (page 686) Adds a child file wrapper to the receiver, which must be a directory file wrapper. – removeFileWrapper: (page 702) Removes a child file wrapper from the receiver, which must be a directory file wrapper. – addRegularFileWithContents:preferredFilename: (page 687) Creates a regular-file file wrapper with the given contents and adds it to the receiver, which must be a directory file wrapper. – keyForFileWrapper: (page 698) Returns the dictionary key used by a directory to identify a given file wrapper. – symbolicLinkDestinationURL (page 706) Provides the URL referenced by the receiver, which must be a symbolic-link file wrapper. – addFileWithPath: (page 685) Available in iOS 4.0 through iOS 4.3 Creates a file wrapper from a given file-system node and adds it to the receiver, which must be a directory file wrapper. (Deprecated. Use addFileWrapper: (page 686) instead.) – addSymbolicLinkWithDestination:preferredFilename: (page 688) Available in iOS 4.0 through iOS 4.3 Creates a symbolic-link file wrapper pointing to a given file-system node and adds it to the receiver, which must be a directory file wrapper. (Deprecated. Use addFileWrapper: (page 686) instead.) – symbolicLinkDestination (page 706) Available in iOS 4.0 through iOS 4.3 Provides the pathname referenced by the receiver, which must be a symbolic-link file wrapper. (Deprecated. Use symbolicLinkDestinationURL (page 706) instead.) NSFileWrapper Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 683Updating File Wrappers – matchesContentsOfURL: (page 698) Indicates whether the contents of a file wrapper matches a directory, regular file, or symbolic link on disk. – readFromURL:options:error: (page 701) Recursively rereads the entire contents of a file wrapper from the specified location on disk. – needsToBeUpdatedFromPath: (page 699) Available in iOS 4.0 through iOS 4.3 Indicates whether the file wrapper needs to be updated to match a given file-system node. (Deprecated. Use matchesContentsOfURL: (page 698) instead.) – updateFromPath: (page 707) Available in iOS 4.0 through iOS 4.3 Updates the file wrapper to match a given file-system node. (Deprecated. Use readFromURL:options:error: (page 701) instead.) Serializing – serializedRepresentation (page 703) Returns the contents of the file wrapper as an opaque collection of data. Accessing Files – filename (page 689) Provides the filename of a file wrapper. – setFilename: (page 704) Specifies the filename of a file wrapper. – preferredFilename (page 700) Provides the preferred filename for a file wrapper. – setPreferredFilename: (page 705) Specifies the receiver’s preferred filename. – fileAttributes (page 689) Returns a file wrapper’s file attributes. – setFileAttributes: (page 704) Specifies a file wrapper’s file attributes. – regularFileContents (page 702) Returns the contents of the file-system node associated with a regular-file file wrapper. NSFileWrapper Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 684Writing Files – writeToURL:options:originalContentsURL:error: (page 709) Recursively writes the entire contents of a file wrapper to a given file-system URL. – writeToFile:atomically:updateFilenames: (page 708) Available in iOS 4.0 through iOS 4.3 Writes a file wrapper’s contents to a given file-system node. (Deprecated. Use writeToURL:options:originalContentsURL:error: (page 709) instead.) Instance Methods addFileWithPath: Creates a file wrapper from a given file-system node and adds it to the receiver, which must be a directory file wrapper. (Available in iOS 4.0 through iOS 4.3. Use addFileWrapper: (page 686) instead.) - (NSString *)addFileWithPath:(NSString *)node Parameters node file-system node from which to create the file wrapper to add to the directory. Return Value Dictionary key used to store the new file wrapper in the directory’s list of file wrappers. See “Working With Directory Wrappers” for more information. Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Instead of using this method, you can instantiate NSFileWrapper with one of the initializers, send it setPreferredFilename: (page 705) if necessary, and pass the result to addFileWrapper: (page 686). This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – addRegularFileWithContents:preferredFilename: (page 687) – addSymbolicLinkWithDestination:preferredFilename: (page 688) – removeFileWrapper: (page 702) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 685– fileWrappers (page 690) Declared in NSFileWrapper.h addFileWrapper: Adds a child file wrapper to the receiver, which must be a directory file wrapper. - (NSString *)addFileWrapper:(NSFileWrapper *)child Parameters child File wrapper to add to the directory. Return Value Dictionary key used to store fileWrapper in the directory’s list of file wrappers. The dictionary key is a unique filename, which is the same as the passed-in file wrapper's preferred filename unless that name is already in use as a key in the directory’s dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure. Discussion Use this method to add an existing file wrapper as a child of a directory file wrapper. If the file wrapper does not have a preferred filename, use the setPreferredFilename: (page 705) method to give it one before calling addFileWrapper:. To create a new file wrapper and add it to a directory, use the addRegularFileWithContents:preferredFilename: (page 687) method. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. This method raises NSInvalidArgumentException if the child file wrapper doesn’t have a preferred name. Availability Available in iOS 4.0 and later. See Also – addRegularFileWithContents:preferredFilename: (page 687) – removeFileWrapper: (page 702) – fileWrappers (page 690) – preferredFilename (page 700) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 686Declared in NSFileWrapper.h addRegularFileWithContents:preferredFilename: Creates a regular-file file wrapper with the given contents and adds it to the receiver, which must be a directory file wrapper. - (NSString *)addRegularFileWithContents:(NSData *)data preferredFilename:(NSString *)filename Parameters data Contents for the new regular-file file wrapper. filename Preferred filename for the new regular-file file wrapper. Return Value Dictionary key used to store the new file wrapper in the directory’s list of file wrappers. The dictionary key is a unique filename, which is the same as the passed-in file wrapper's preferred filename unless that name is already in use as a key in the directory's dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure. Discussion This is a convenience method. The default implementation allocates a new file wrapper, initializes it with initRegularFileWithContents: (page 691), sends it setPreferredFilename: (page 705), adds it to the directory with addFileWrapper: (page 686), and returns what addFileWrapper: returned. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. This method raises NSInvalidArgumentException if you pass nil or an empty value for filename. Availability Available in iOS 4.0 and later. See Also – addFileWrapper: (page 686) – removeFileWrapper: (page 702) – fileWrappers (page 690) Declared in NSFileWrapper.h NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 687addSymbolicLinkWithDestination:preferredFilename: Creates a symbolic-link file wrapper pointing to a given file-system node and adds it to the receiver, which must be a directory file wrapper. (Available in iOS 4.0 through iOS 4.3. Use addFileWrapper: (page 686) instead.) - (NSString *)addSymbolicLinkWithDestination:(NSString *)node preferredFilename:(NSString *)preferredFilename Parameters node Pathname the new symbolic-link file wrapper is to reference. preferredFilename Preferred filename for the new symbolic-link file wrapper. Return Value Dictionary key used to store the new file wrapper in the directory’s list of file wrappers. See “Working With Directory Wrappers” for more information. Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Instead of using this method, you can instantiate NSFileWrapper with one of the initializers, send it setPreferredFilename: (page 705) if necessary, and pass the result to addFileWrapper: (page 686). This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. This method raises NSInvalidArgumentException if you pass nil or an empty value for preferredFilename. Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – addFileWrapper: (page 686) – addRegularFileWithContents:preferredFilename: (page 687) – removeFileWrapper: (page 702) – fileWrappers (page 690) Declared in NSFileWrapper.h NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 688fileAttributes Returns a file wrapper’s file attributes. - (NSDictionary *)fileAttributes Return Value File attributes, in a dictionary of the same sort as that returned by attributesOfItemAtPath:error: (page 610) (NSFileManager). Availability Available in iOS 4.0 and later. See Also – setFileAttributes: (page 704) Declared in NSFileWrapper.h filename Provides the filename of a file wrapper. - (NSString *)filename Return Value The file wrapper’s filename; nil when the file wrapper has no corresponding file-system node. Discussion The filename is used for record-keeping purposes only and is set automatically when the file wrapper is created from the file system using initWithURL:options:error: (page 695) and when it’s saved to the file system using writeToURL:options:originalContentsURL:error: (page 709) (although this method allows you to request that the filename not be updated). The filename is usually the same as the preferred filename, but might instead be a name derived from the preferred filename. You can use this method to get the name of a child that's just been read. Don’t use this method to get the name of a child that's about to be written, because the name might be about to change; send keyForFileWrapper: (page 698) to the parent instead. Availability Available in iOS 4.0 and later. See Also – preferredFilename (page 700) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 689– setFilename: (page 704) Declared in NSFileWrapper.h fileWrappers Returns the file wrappers contained by a directory file wrapper. - (NSDictionary *)fileWrappers Return Value A key-value dictionary of the file wrappers contained in the directory. The dictionary contains entries whose values are the file wrappers and whose keys are the unique filenames that have been assigned to each one. See “Working With Directory Wrappers” in ApplicationFileManagement for more information about the file-wrapper list structure. Discussion Returns a dictionary whose values are the file wrapper's children and whose keys are the unique filenames that have been assigned to each one. This method may return nil if the user modifies the directory after you call readFromURL:options:error: (page 701) or initWithURL:options:error: (page 695) but before NSFileWrapper has read the contents of the directory. Use the NSFileWrapperReadingImmediate reading option to reduce the likelihood of that problem. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. Availability Available in iOS 4.0 and later. See Also – filename (page 689) – addFileWrapper: (page 686) Declared in NSFileWrapper.h initDirectoryWithFileWrappers: Initializes the receiver as a directory file wrapper, with a given file-wrapper list. - (id)initDirectoryWithFileWrappers:(NSDictionary *)childrenByPreferredName NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 690Parameters childrenByPreferredName Key-value dictionary of file wrappers with which to initialize the receiver. The dictionary must contain entries whose values are the file wrappers that are to become children and whose keys are filenames. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure. Return Value Initialized file wrapper for fileWrappers. Discussion After initialization, the file wrapper is not associated with a file-system node until you save it using writeToURL:options:originalContentsURL:error: (page 709). The receiver is initialized with open permissions: anyone can read, write, or modify the directory on disk. If any file wrapper in the directory doesn’t have a preferred filename, its preferred name is automatically set to its corresponding key in the childrenByPreferredName dictionary. Availability Available in iOS 4.0 and later. See Also – setPreferredFilename: (page 705) – filename (page 689) – setFileAttributes: (page 704) Declared in NSFileWrapper.h initRegularFileWithContents: Initializes the receiver as a regular-file file wrapper. - (id)initRegularFileWithContents:(NSData *)contents Parameters contents Contents of the file. Return Value Initialized regular-file file wrapper containing contents. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 691Discussion After initialization, the file wrapper is not associated with a file-system node until you save it using writeToURL:options:originalContentsURL:error: (page 709). The file wrapper is initialized with open permissions: anyone can write to or read the file wrapper. . Availability Available in iOS 4.0 and later. See Also – setPreferredFilename: (page 705) – filename (page 689) – fileAttributes (page 689) – regularFileContents (page 702) Declared in NSFileWrapper.h initSymbolicLinkWithDestination: Initializes the receiver as a symbolic-link file wrapper. (Available in iOS 4.0 through iOS 4.3. Use initSymbolicLinkWithDestinationURL: (page 693) instead.) - (id)initSymbolicLinkWithDestination:(NSString *)node Parameters node Pathname the receiver is to represent. Return Value Initialized symbolic-link file wrapper referencing node. Discussion The receiver is not associated to a file-system node until you save it using writeToFile:atomically:updateFilenames: (page 708). It’s also initialized with open permissions; anyone can read or write the disk representations it saves. Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Therefore, this method has been deprecated in favor of initSymbolicLinkWithDestinationURL: (page 693). NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 692Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – setPreferredFilename: (page 705) – filename (page 689) – fileAttributes (page 689) Declared in NSFileWrapper.h initSymbolicLinkWithDestinationURL: Initializes the receiver as a symbolic-link file wrapper that links to a specified file. - (id)initSymbolicLinkWithDestinationURL:(NSURL *)url Parameters url URL of the file the file wrapper is to reference. Return Value Initialized symbolic-link file wrapper referencing url. Discussion The file wrapper is not associated with a file-system node until you save it using writeToURL:options:originalContentsURL:error: (page 709). The file wrapper is initialized with open permissions: anyone can modify or read the file reference. . Availability Available in iOS 4.0 and later. See Also – setPreferredFilename: (page 705) – filename (page 689) – fileAttributes (page 689) Declared in NSFileWrapper.h NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 693initWithPath: Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the path. (Available in iOS 4.0 through iOS 4.3. Use initWithURL:options:error: (page 695) instead.) - (id)initWithPath:(NSString *)node Parameters node Pathname of the file-system node the file wrapper is to represent. Return Value File wrapper for node. Discussion If node is a directory, this method recursively creates file wrappers for each node within that directory. Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Therefore, this method has been deprecated in favor of initWithURL:options:error: (page 695). Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – setPreferredFilename: (page 705) – filename (page 689) – fileAttributes (page 689) Declared in NSFileWrapper.h initWithSerializedRepresentation: Initializes the receiver as a regular-file file wrapper from given serialized data. - (id)initWithSerializedRepresentation:(NSData *)serializedRepresentation NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 694Parameters serializedRepresentation Serialized representation of a file wrapper in the format used for the NSFileContentsPboardType pasteboard type. Data of this format is returned by such methods as serializedRepresentation (page 703) and RTFDFromRange:documentAttributes: (NSAttributedString). Return Value Regular-file file wrapper initialized from serializedRepresentation. Discussion The file wrapper is not associated with a file-system node until you save it using writeToURL:options:originalContentsURL:error: (page 709). Availability Available in iOS 4.0 and later. See Also – setPreferredFilename: (page 705) – filename (page 689) – fileAttributes (page 689) Declared in NSFileWrapper.h initWithURL:options:error: Initializes a file wrapper instance whose kind is determined by the type of file-system node located by the URL. - (id)initWithURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError Parameters url URL of the file-system node the file wrapper is to represent. options Option flags for reading the node located at url. See “File Wrapper Reading Options” (page 710) for possible values. outError If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 695Return Value File wrapper for the file-system node at url. May be a directory, file, or symbolic link, depending on what is located at the URL. Returns NO (0) if reading is not successful. Discussion If url is a directory, this method recursively creates file wrappers for each node within that directory. Use the fileWrappers (page 690) method to get the file wrappers of the nodes contained by the directory. Availability Available in iOS 4.0 and later. See Also – fileWrappers (page 690) – setPreferredFilename: (page 705) – filename (page 689) – fileAttributes (page 689) – readFromURL:options:error: (page 701) Declared in NSFileWrapper.h isDirectory Indicates whether the receiver is a directory file wrapper. - (BOOL)isDirectory Return Value YES when the receiver is a directory file wrapper, NO otherwise. Discussion Invocations of readFromURL:options:error: (page 701) may change what is returned by subsequent invocations of this method if the type of the file on disk has changed. Availability Available in iOS 4.0 and later. See Also – isRegularFile (page 697) – isSymbolicLink (page 697) Declared in NSFileWrapper.h NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 696isRegularFile Indicates whether the receiver is a regular-file file wrapper. - (BOOL)isRegularFile Return Value YES when the receiver is a regular-file wrapper, NO otherwise. Discussion Invocations of readFromURL:options:error: (page 701) may change what is returned by subsequent invocations of this method if the type of the file on disk has changed. Availability Available in iOS 4.0 and later. See Also – isDirectory (page 696) – isSymbolicLink (page 697) Declared in NSFileWrapper.h isSymbolicLink Indicates whether the receiver is a symbolic-link file wrapper. - (BOOL)isSymbolicLink Return Value YES when the receiver is a symbolic-link file wrapper, NO otherwise. Discussion Invocations of readFromURL:options:error: (page 701) may change what is returned by subsequent invocations of this method if the type of the file on disk has changed. Availability Available in iOS 4.0 and later. See Also – isDirectory (page 696) – isRegularFile (page 697) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 697Declared in NSFileWrapper.h keyForFileWrapper: Returns the dictionary key used by a directory to identify a given file wrapper. - (NSString *)keyForFileWrapper:(NSFileWrapper *)child Parameters child The child file wrapper for which you want the key. Return Value Dictionary key used to store the file wrapper in the directory’s list of file wrappers. The dictionary key is a unique filename, which may not be the same as the passed-in file wrapper's preferred filename if more than one file wrapper in the directory's dictionary of children has the same preferred filename. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure. Returns nil if the file wrapper specified in child is not a child of the directory. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. Availability Available in iOS 4.0 and later. See Also – filename (page 689) Declared in NSFileWrapper.h matchesContentsOfURL: Indicates whether the contents of a file wrapper matches a directory, regular file, or symbolic link on disk. - (BOOL)matchesContentsOfURL:(NSURL *)url Parameters url URL of the file-system node with which to compare the file wrapper. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 698Return Value YES when the contents of the file wrapper match the contents of url, NO otherwise. Discussion The contents of files are not compared; matching of regular files is based on file modification dates. For a directory, children are compared against the files in the directory, recursively. Because children of directory file wrappers are not read immediately by the initWithURL:options:error: (page 695) method unless the NSFileWrapperReadingImmediate reading option is used, even a newly-created directory file wrapper might not have the same contents as the directory on disk. You can use this method to determine whether the file wrapper's contents in memory need to be updated. If the file wrapper needs updating, use the readFromURL:options:error: (page 701) method with the NSFileWrapperReadingImmediate reading option. This table describes which attributes of the file wrapper and file-system node are compared to determine whether the file wrapper matches the node on disk: Comparison determinantsFile-wrapper type Modification date and access permissions.Regular file Children (recursive).Directory Destination pathname.Symbolic link Availability Available in iOS 4.0 and later. See Also – readFromURL:options:error: (page 701) – fileAttributes (page 689) Declared in NSFileWrapper.h needsToBeUpdatedFromPath: Indicates whether the file wrapper needs to be updated to match a given file-system node. (Available in iOS 4.0 through iOS 4.3. Use matchesContentsOfURL: (page 698) instead.) - (BOOL)needsToBeUpdatedFromPath:(NSString *)node NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 699Parameters node file-system node with which to compare the file wrapper. Return Value YES when the file wrapper needs to be updated to match node, NO otherwise. Discussion This table describes which attributes of the file wrapper and node are compared to determine whether the file wrapper needs to be updated: Comparison determinantsFile-wrapper type Modification date and access permissions.Regular file Member hierarchy (recursive).Directory Destination pathname.Symbolic link Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Therefore, this method has been deprecated in favor of matchesContentsOfURL: (page 698). Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – updateFromPath: (page 707) – fileAttributes (page 689) Declared in NSFileWrapper.h preferredFilename Provides the preferred filename for a file wrapper. - (NSString *)preferredFilename Return Value The file wrapper’s preferred filename. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 700Discussion This name is normally used as the dictionary key when a child file wrapper is added to a directory file wrapper. However, if another file wrapper with the same preferred name already exists in the directory file wrapper when the receiver is added, the filename assigned as the dictionary key may differ from the preferred filename. Availability Available in iOS 4.0 and later. See Also – filename (page 689) – setPreferredFilename: (page 705) Declared in NSFileWrapper.h readFromURL:options:error: Recursively rereads the entire contents of a file wrapper from the specified location on disk. - (BOOL)readFromURL:(NSURL *)url options:(NSFileWrapperReadingOptions)options error:(NSError **)outError Parameters url URL of the file-system node corresponding to the file wrapper. options Option flags for reading the node located at url. See “File Wrapper Reading Options” (page 710) for possible values. outError If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value YES if successful. If not successful, returns NO after setting outError to an NSError object that describes the reason why the file wrapper could not be reread. Discussion When reading a directory, children are added and removed as necessary to match the file system. Availability Available in iOS 4.0 and later. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 701See Also – initWithURL:options:error: (page 695) – fileWrappers (page 690) – filename (page 689) – fileAttributes (page 689) – writeToURL:options:originalContentsURL:error: (page 709) Declared in NSFileWrapper.h regularFileContents Returns the contents of the file-system node associated with a regular-file file wrapper. - (NSData *)regularFileContents Return Value Contents of the file-system node the file wrapper represents. Discussion This method may return nil if the user modifies the file after you call readFromURL:options:error: (page 701) or initWithURL:options:error: (page 695) but before NSFileWrapper has read the contents of the file. Use the NSFileWrapperReadingImmediate reading option to reduce the likelihood of that problem. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a regular-file file wrapper. Availability Available in iOS 4.0 and later. See Also – initRegularFileWithContents: (page 691) – readFromURL:options:error: (page 701) Declared in NSFileWrapper.h removeFileWrapper: Removes a child file wrapper from the receiver, which must be a directory file wrapper. - (void)removeFileWrapper:(NSFileWrapper *)child NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 702Parameters child File wrapper to remove from the directory. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a directory file wrapper. Availability Available in iOS 4.0 and later. See Also – addFileWrapper: (page 686) – addRegularFileWithContents:preferredFilename: (page 687) – fileWrappers (page 690) Declared in NSFileWrapper.h serializedRepresentation Returns the contents of the file wrapper as an opaque collection of data. - (NSData *)serializedRepresentation Return Value The file wrapper’s contents in the format used for the pasteboard type NSFileContentsPboardType. Discussion Returns an NSData object suitable for passing to initWithSerializedRepresentation: (page 694). This method may return nil if the user modifies the contents of the file-system node after you call readFromURL:options:error: (page 701) or initWithURL:options:error: (page 695) but before NSFileWrapper has read the contents of the file. Use the NSFileWrapperReadingImmediate reading option to reduce the likelihood of that problem. Availability Available in iOS 4.0 and later. See Also – initWithSerializedRepresentation: (page 694) Declared in NSFileWrapper.h NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 703setFileAttributes: Specifies a file wrapper’s file attributes. - (void)setFileAttributes:(NSDictionary *)fileAttributes Parameters fileAttributes File attributes for the file wrapper, in a dictionary of the same sort as that used by setAttributes:ofItemAtPath:error: (page 656) (NSFileManager). Availability Available in iOS 4.0 and later. See Also – fileAttributes (page 689) – writeToURL:options:originalContentsURL:error: (page 709) Declared in NSFileWrapper.h setFilename: Specifies the filename of a file wrapper. - (void)setFilename:(NSString *)filename Parameters filename Filename of the file wrapper. Discussion The file name is a dictionary key used to store fileWrapper in a directory’s list of child file wrappers. The dictionary key is a unique filename, which is the same as the child file wrapper's preferred filename unless that name is already in use as a key in the directory’s dictionary of children. See “Working With Directory Wrappers” in Application File Management for more information about the file-wrapper list structure. In general, the filename is set for you by the initWithURL:options:error: (page 695), initDirectoryWithFileWrappers: (page 690), or writeToURL:options:originalContentsURL:error: (page 709) methods; you do not normally have to call this method directly. Special Considerations This method raises NSInvalidArgumentException if you pass nil or an empty value for filename. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 704Availability Available in iOS 4.0 and later. See Also – filename (page 689) – setPreferredFilename: (page 705) – initWithURL:options:error: (page 695) – initDirectoryWithFileWrappers: (page 690) – writeToURL:options:originalContentsURL:error: (page 709) Declared in NSFileWrapper.h setPreferredFilename: Specifies the receiver’s preferred filename. - (void)setPreferredFilename:(NSString *)filename Parameters filename Preferred filename for the receiver. Discussion When a file wrapper is added to a parent directory file wrapper, the parent attempts to use the child’s preferred filename as the key in its dictionary of children. If that key is already in use, then the parent derives a unique filename from the preferred filename and uses that for the key. When you change the preferred filename of a file wrapper, the default implementation of this method causes existing parent directory file wrappers to remove and re-add the child to accommodate the change. Preferred filenames of children are not preserved when you write a file wrapper to disk and then later instantiate another file wrapper by reading the file from disk. If you need to preserve the user-visible names of attachments, you have to store the names yourself. Special Considerations This method raises NSInvalidArgumentException if you pass nil or an empty value for filename. Availability Available in iOS 4.0 and later. See Also – preferredFilename (page 700) – setFilename: (page 704) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 705– addFileWrapper: (page 686) – initWithURL:options:error: (page 695) – initDirectoryWithFileWrappers: (page 690) – writeToURL:options:originalContentsURL:error: (page 709) Declared in NSFileWrapper.h symbolicLinkDestination Provides the pathname referenced by the receiver, which must be a symbolic-link file wrapper. (Available in iOS 4.0 through iOS 4.3. Use symbolicLinkDestinationURL (page 706) instead.) - (NSString *)symbolicLinkDestination Return Value Pathname the file wrapper references (the destination of the symbolic link the file wrapper represents). Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Therefore, this method has been deprecated in favor of symbolicLinkDestinationURL (page 706). This method raises NSInternalInconsistencyException if the receiver is not a symbolic-link file wrapper. Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. Declared in NSFileWrapper.h symbolicLinkDestinationURL Provides the URL referenced by the receiver, which must be a symbolic-link file wrapper. - (NSURL *)symbolicLinkDestinationURL Return Value Pathname the file wrapper references (that is, the destination of the symbolic link the file wrapper represents). NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 706Discussion This method may return nil if the user modifies the symbolic link after you call readFromURL:options:error: (page 701) or initWithURL:options:error: (page 695) but before NSFileWrapper has read the contents of the link. Use the NSFileWrapperReadingImmediate reading option to reduce the likelihood of that problem. Special Considerations This method raises NSInternalInconsistencyException if the receiver is not a symbolic-link file wrapper. Availability Available in iOS 4.0 and later. Declared in NSFileWrapper.h updateFromPath: Updates the file wrapper to match a given file-system node. (Available in iOS 4.0 through iOS 4.3. Use readFromURL:options:error: (page 701) instead.) - (BOOL)updateFromPath:(NSString *)path Return Value YES if the update is carried out, NO if it isn’t needed. Discussion For a directory file wrapper, the contained file wrappers are also sent updateFromPath: messages. If nodes in the corresponding directory on the file system have been added or removed, corresponding file wrappers are released or created as needed. Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Therefore, this method has been deprecated in favor of readFromURL:options:error: (page 701). Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – needsToBeUpdatedFromPath: (page 699) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 707Declared in NSFileWrapper.h writeToFile:atomically:updateFilenames: Writes a file wrapper’s contents to a given file-system node. (Available in iOS 4.0 through iOS 4.3. Use writeToURL:options:originalContentsURL:error: (page 709) instead.) - (BOOL)writeToFile:(NSString *)node atomically:(BOOL)atomically updateFilenames:(BOOL)updateNames Parameters node Pathname of the file-system node to which the receiver’s contents are written. atomically YES to write the file safely so that: ● An existing file is not overwritten ● The method fails if the file cannot be written in its entirety NO to overwrite an existing file and ignore incomplete writes. updateNames YES to update the receiver’s filenames (its filename and—for directory file wrappers—the filenames of its sub–file wrappers) be changed to the filenames of the corresponding nodes in the file system, after a successful write operation. Use this in Save or Save As operations. NO to specify that the receiver’s filenames not be updated. Use this in Save To operations. Return Value YES when the write operation is successful, NO otherwise. Special Considerations Beginning with Mac OS X v10.6, the preferred method of referring to files is with a file:// URL. Therefore, this method has been deprecated in favor of writeToURL:options:originalContentsURL:error: (page 709). Availability Available in iOS 4.0 through iOS 4.3. Deprecated in iOS 4.0. See Also – filename (page 689) – writeToURL:options:originalContentsURL:error: (page 709) NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 708Declared in NSFileWrapper.h writeToURL:options:originalContentsURL:error: Recursively writes the entire contents of a file wrapper to a given file-system URL. - (BOOL)writeToURL:(NSURL *)url options:(NSFileWrapperWritingOptions)options originalContentsURL:(NSURL *)originalContentsURL error:(NSError **)outError Parameters url URL of the file-system node to which the file wrapper’s contents are written. options Option flags for writing to the node located at url. See “File Wrapper Writing Options” (page 711) for possible values. originalContentsURL The location of a previous revision of the contents being written. The default implementation of this method attempts to avoid unnecessary I/O by writing hard links to regular files instead of actually writing out their contents when the contents have not changed. The child file wrappers must return accurate values when sent the filename (page 689) method for this to work. Use the NSFileWrapperWritingWithNameUpdating writing option to increase the likelihood of that. Specify nil for this parameter if there is no earlier version of the contents or if you want to ensure that all the contents are written to files. updateNames YES to update the receiver’s filenames (its filename and—for directory file wrappers—the filenames of its sub–file wrappers) be changed to the filenames of the corresponding nodes in the file system, after a successful write operation. Use this in Save or Save As operations. NO to specify that the receiver’s filenames not be updated. Use this in Save To operations. outError If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information. Return Value YES when the write operation is successful. If not successful, returns NO after setting outError to an NSError object that describes the reason why the file wrapper’s contents could not be written. Availability Available in iOS 4.0 and later. NSFileWrapper Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 709See Also – filename (page 689) – readFromURL:options:error: (page 701) Declared in NSFileWrapper.h Constants File Wrapper Reading Options Reading options that can be set by the initWithURL:options:error: (page 695) and readFromURL:options:error: (page 701) methods. enum { NSFileWrapperReadingImmediate = 1 << 0, NSFileWrapperReadingWithoutMapping = 1 << 1 }; typedef NSUInteger NSFileWrapperReadingOptions; Constants NSFileWrapperReadingImmediate If reading with this option succeeds, then subsequent invocations of fileWrappers (page 690), regularFileContents (page 702), symbolicLinkDestinationURL (page 706), and serializedRepresentation (page 703) sent to the file wrapper and all its child file wrappers will fail and return nil only if an actual error occurs (for example, the volume has disappeared or the file server is unreachable)—not as a result of the user moving or deleting files. For performance reasons, NSFileWrapper may not read the contents of some file packages immediately even when this option is chosen. For example, because the contents of bundles (not all file packages are bundles) are immutable to the user, NSFileWrapper may read the children of such a directory lazily. You can use this option to take a snapshot of a file or folder for writing later. For example, an application like TextEdit can use this option when creating new file wrappers to represent attachments that the user creates by copying and pasting or dragging and dropping from the Finder to a TextEdit document. Don't use this option when reading a document file package, because that would cause unnecessarily bad performance. For example, an application wouldn't use this option when creating file wrappers to represent attachments as it's opening a document stored in a file package. Available in iOS 4.0 and later. Declared in NSFileWrapper.h. NSFileWrapper Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 710NSFileWrapperReadingWithoutMapping Whether file mapping for regular file wrappers is disallowed. You can use this option to keep NSFileWrapper from memory-mapping files. This is useful if you want to make sure your application doesn't hold files open (mapped files are open files), therefore preventing the user from ejecting DVDs, unmounting disk partitions, or unmounting disk images. In Mac OS X v10.6 and later, NSFileWrapper memory-maps files that are on internal drives only. It never memory-maps files on external drives or network volumes, regardless of whether this option is used. Available in iOS 4.0 and later. Declared in NSFileWrapper.h. Discussion You can use the NSFileWrapperReadingImmediate and NSFileWrapperReadingWithoutMapping reading options together to take an exact snapshot of a file-system hierarchy that is safe from all errors (including the ones mentioned above) once reading has succeeded. If reading with both options succeeds, then subsequent invocations of the methods listed in the comment for the NSFileWrapperReadingImmediate reading option to the receiver and all its descendant file wrappers will never fail. However, note that reading with both options together is expensive in terms of both I/O and memory for large files, or directories containing large files, or even directories containing many small files. File Wrapper Writing Options Writingoptionsthatcanbesetbythe writeToURL:options:originalContentsURL:error: (page 709)method. enum { NSFileWrapperWritingAtomic = 1 << 0, NSFileWrapperWritingWithNameUpdating = 1 << 1 }; typedef NSUInteger NSFileWrapperWritingOptions; Constants NSFileWrapperWritingAtomic Whether writing is done atomically. You can use this option to ensure that, when overwriting a file package, the overwriting either completely succeeds or completely fails, with no possibility of leaving the file package in an inconsistent state. Because this option causes additional I/O, you shouldn't use it unnecessarily. For example, don't use this option in an override of -[NSDocument writeToURL:ofType:error:], because NSDocument safe-saving is already done atomically. Available in iOS 4.0 and later. Declared in NSFileWrapper.h. NSFileWrapper Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 711NSFileWrapperWritingWithNameUpdating Whether descendant file wrappers are sent the setFilename: (page 704) method if the writing succeeds. This option is necessary when your application passes a URL in the originalContentsURL parameter to the writeToURL:options:originalContentsURL:error: (page 709) method. Without using this option (and reusing child file wrappers properly), subsequent invocations of writeToURL:options:originalContentsURL:error: (page 709) would not be able to reliably create hard links in a new file package, because the record of names in the old file package would be out of date. Available in iOS 4.0 and later. Declared in NSFileWrapper.h. NSFileWrapper Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 712Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSFormatter.h Companion guide Data Formatting Guide Overview NSFormatter is an abstract class that declares an interface for objects that create, interpret, and validate the textual representation of cell contents. The Foundation framework provides two concrete subclasses of NSFormatter to generate these objects: NSNumberFormatter and NSDateFormatter. Subclassing Notes NSFormatter is intended for subclassing. A custom formatter can restrict the input and enhance the display of data in novel ways. For example, you could have a custom formatter that ensures that serial numbers entered by a user conform to predefined formats. Before you decide to create a custom formatter, make sure that you cannot configure the public subclasses NSDateFormatter and NSNumberFormatter to satisfy your requirements. For instructions on how to create your own custom formatter, see Creating a Custom Formatter. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 713 NSFormatter Class ReferenceTasks Textual Representation of Cell Content – stringForObjectValue: (page 720) The default implementation of this method raises an exception. – attributedStringForObjectValue:withDefaultAttributes: (page 714) The default implementation returns nil to indicate that the formatter object does not provide an attributed string. – editingStringForObjectValue: (page 715) The default implementation of this method invokes stringForObjectValue: (page 720). Object Equivalent to Textual Representation – getObjectValue:forString:errorDescription: (page 716) The default implementation of this method raises an exception. Dynamic Cell Editing – isPartialStringValid:newEditingString:errorDescription: (page 718) Returns a Boolean value that indicates whether a partial string is valid. – isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange:errorDescription: (page 719) This method should be implemented in subclasses that want to validate user changes to a string in a field, where the user changes are not necessarily at the end of the string, and preserve the selection (or set a different one, such as selecting the erroneous part of the string the user has typed). Instance Methods attributedStringForObjectValue:withDefaultAttributes: The default implementation returns nil to indicate that the formatter object does not provide an attributed string. NSFormatter Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 714- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes:(NSDictionary *)attributes Parameters anObject The object for which a textual representation is returned. attributes The default attributes to use for the returned attributed string. Return Value An attributed string that represents anObject. Discussion When implementing a subclass, return an NSAttributedString object if the string for display should have some attributes. For instance, you might want negative values in a financial application to appear in red text. Invoke your implementation of stringForObjectValue: (page 720) to get the non-attributed string, then create an NSAttributedString object with it (see initWithString: (page 112)). Use the attributes default dictionary to reset the attributes of the string when a change in value warrants it (for example, a negative value becomes positive) For information on creating attributed strings, see Attributed String Programming Guide. Availability Available in iOS 2.0 and later. See Also – editingStringForObjectValue: (page 715) Declared in NSFormatter.h editingStringForObjectValue: The default implementation of this method invokes stringForObjectValue: (page 720). - (NSString *)editingStringForObjectValue:(id)anObject Parameters anObject The object for which to return an editing string. Return Value An NSString object that is used for editing the textual representation of anObject. NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 715Discussion When implementing a subclass, override this method only when the string that users see and the string that they edit are different. In your implementation, return an NSString object that is used for editing, following the logic recommended for implementing stringForObjectValue: (page 720). As an example, you would implement this method if you want the dollar signs in displayed strings removed for editing. Availability Available in iOS 2.0 and later. See Also – attributedStringForObjectValue:withDefaultAttributes: (page 714) Declared in NSFormatter.h getObjectValue:forString:errorDescription: The default implementation of this method raises an exception. - (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error Parameters anObject If conversion is successful, upon return contains the object created from string. string The string to parse. error If non-nil, if there is a error during the conversion, upon return contains an NSString object that describes the problem. Return Value YES if the conversion from string to cell content object was successful, otherwise NO. Discussion When implementing a subclass, return by reference the object anObject after creating it from string. Return YES if the conversion is successful. If you return NO, also return by indirection (in error) a localized user-presentable NSString object that explains the reason why the conversion failed; the delegate (if any) of the NSControl object managing the cell can then respond to the failure in control:didFailToFormatString:errorDescription:. However, if error is nil, the sender is not interested in the error description, and you should not attempt to assign one. NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 716The following example (which is paired with the example given in stringForObjectValue: (page 720)) converts a string representation of a dollar amount that includes the dollar sign; it uses an NSScanner instance to convert this amount to a float after stripping out the initial dollar sign. - (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString **)error { float floatResult; NSScanner *scanner; BOOL returnValue = NO; scanner = [NSScanner scannerWithString: string]; [scanner scanString: @"$" intoString: NULL]; //ignore return value if ([scanner scanFloat:&floatResult] && ([scanner isAtEnd])) { returnValue = YES; if (obj) *obj = [NSNumber numberWithFloat:floatResult]; } else { if (error) *error = NSLocalizedString(@"Couldn’t convert to float", @"Error converting"); } return returnValue; } Special Considerations Prior to Mac OS X v10.6, the implementation of this method in both NSNumberFormatter and NSDateFormatter would return YES and an object value even if only part of the string could be parsed. This is problematic because you cannot be sure what portion of the string was parsed. For applications linked on or after Mac OS X v10.6, this method instead returns an error if part of the string cannot be parsed. You can use getObjectValue:forString:range:error: to get the old behavior—it returns the range of the substring that was successfully parsed. Availability Available in iOS 2.0 and later. See Also – stringForObjectValue: (page 720) NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 717Declared in NSFormatter.h isPartialStringValid:newEditingString:errorDescription: Returns a Boolean value that indicates whether a partial string is valid. - (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error Parameters partialString The text currently in a cell. newString If partialString needs to be modified, upon return contains the replacement string. error If non-nil, if validation fails contains an NSString object that describes the problem. Return Value YES if partialString is an acceptable value, otherwise NO. Discussion This method is invoked each time the user presses a key while the cell has the keyboard focus—it lets you verify and edit the cell text as the user types it. In a subclass implementation, evaluate partialString according to the context, edit the text if necessary, and return by reference any edited string in newString. Return YES if partialString is acceptable and NO if partialString is unacceptable. If you return NO and newString is nil, the cell displays partialString minus the last character typed. If you return NO, you can also return by indirection an NSString object (in error) that explains the reason why the validation failed; the delegate (if any) of the NSControl object managing the cell can then respond to the failure in control:didFailToValidatePartialString:errorDescription:. The selection range will always be set to the end of the text if replacement occurs. This method is a compatibility method. If a subclass overrides this method and does not override isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange: errorDescription: (page 719), this method will be called as before (isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange: errorDescription: (page 719) just calls this one by default). NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 718Availability Available in iOS 2.0 and later. Declared in NSFormatter.h isPartialStringValid:proposedSelectedRange:originalString:originalSelectedRange: errorDescription: This method should be implemented in subclasses that want to validate user changes to a string in a field, where the user changes are not necessarily at the end of the string, and preserve the selection (or set a different one, such as selecting the erroneous part of the string the user has typed). - (BOOL)isPartialStringValid:(NSString **)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString **)error Parameters partialStringPtr The new string to validate. proposedSelRangePtr The selection range that will be used if the string is accepted or replaced. origString The original string, before the proposed change. origSelRange The selection range over which the change is to take place. error If non-nil, if validation fails contains an NSString object that describes the problem. Return Value YES if partialStringPtr is acceptable, otherwise NO. Discussion In a subclass implementation, evaluate partialString according to the context. Return YES if partialStringPtr is acceptable and NO if partialStringPtr is unacceptable. Assign a new string to partialStringPtr and a new range to proposedSelRangePtr and return NO if you want to replace the string and change the selection range. If you return NO, you can also return by indirection an NSString object NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 719(in error) that explains the reason why the validation failed; the delegate (if any) of the NSControl object managing the cell can then respond to the failure in control:didFailToValidatePartialString:errorDescription:. Availability Available in iOS 2.0 and later. See Also – isPartialStringValid:newEditingString:errorDescription: (page 718) Declared in NSFormatter.h stringForObjectValue: The default implementation of this method raises an exception. - (NSString *)stringForObjectValue:(id)anObject Parameters anObject The object for which a textual representation is returned. Return Value An NSString object that textually represents object for display. Returns nil if object is not of the correct class. Discussion When implementing a subclass, return the NSString object that textually represents the cell’s object for display and—if editingStringForObjectValue: (page 715) is unimplemented—for editing. First test the passed-in object to see if it’s of the correct class. If it isn’t, return nil; but if it is of the right class, return a properly formatted and, if necessary, localized string. (See the specification of the NSString class for formatting and localizing details.) The following implementation (which is paired with the getObjectValue:forString:errorDescription: (page 716) example above) prefixes a two-digit float representation with a dollar sign: - (NSString *)stringForObjectValue:(id)anObject { if (![anObject isKindOfClass:[NSNumber class]]) { return nil; NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 720} return [NSString stringWithFormat:@"$%.2f", [anObject floatValue]]; } Availability Available in iOS 2.0 and later. See Also – attributedStringForObjectValue:withDefaultAttributes: (page 714) – editingStringForObjectValue: (page 715) – getObjectValue:forString:errorDescription: (page 716) Declared in NSFormatter.h NSFormatter Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 721Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Declared in Foundation/NSHTTPCookie.h Availability Available in iOS 2.0 and later. Companion guide URL Loading System Programming Guide Overview An NSHTTPCookie object represents an HTTP cookie. It’s an immutable object initialized from a dictionary containing the cookie attributes. Two versions of cookies are supported: ● Version 0: This version refers to “traditional” or “old-style” cookies, the original cookie format defined by Netscape. The majority of cookies encountered are in this format. ● Version 1: This version refers to cookies as defined in RFC 2965, HTTP State Management Mechanism. Adopted Protocols NSCopying – copyWithZone: (page 2002) 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 722 NSHTTPCookie Class ReferenceTasks Create Cookie Instances + cookiesWithResponseHeaderFields:forURL: (page 724) Returns an array of NSHTTPCookie objects corresponding to the provided response header fields for the provided URL. + cookieWithProperties: (page 725) Creates and initializes an NSHTTPCookie object using the provided properties. – initWithProperties: (page 728) Returns an initialized NSHTTPCookie object using the provided properties. Convert Cookies to Request Headers + requestHeaderFieldsWithCookies: (page 725) Returns a dictionary of header fields corresponding to a provided array of cookies. Getting Cookie Properties – comment (page 726) Returns the receiver's comment string. – commentURL (page 726) Returns the receiver’s comment URL. – domain (page 727) Returns the domain of the receiver’s cookie. – expiresDate (page 727) Returns the receiver’s expiration date. – isHTTPOnly (page 728) Returns whether the receiver should only be sent to HTTP servers per RFC 2965. – isSecure (page 729) Returns whether his cookie should only be sent over secure channels. – isSessionOnly (page 729) Returns whether the receiver should be discarded at the end of the session (regardless of expiration date). NSHTTPCookie Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 723– name (page 730) Returns the receiver’s name. – path (page 730) Returns the receiver’s path. – portList (page 730) Returns the receiver's port list. – properties (page 731) Returns the receiver’s cookie properties. – value (page 731) Returns the receiver’s value. – version (page 732) Returns the receiver’s version. Class Methods cookiesWithResponseHeaderFields:forURL: Returns an array of NSHTTPCookie objects corresponding to the provided response header fields for the provided URL. + (NSArray *)cookiesWithResponseHeaderFields:(NSDictionary *)headerFields forURL:(NSURL *)theURL Parameters headerFields The header fields used to create the NSHTTPCookie objects. theURL The URL associated with the created cookies. Return Value The array of created cookies. Discussion This method ignores irrelevant header fields in headerFields, allowing dictionaries to contain additional data. NSHTTPCookie Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 724If headerFields does not specify a domain for a given cookie, the cookie is created with a default domain value of theURL. If headerFields does not specify a path for a given cookie, the cookie is created with a default path value of “/”. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h cookieWithProperties: Creates and initializes an NSHTTPCookie object using the provided properties. + (id)cookieWithProperties:(NSDictionary *)properties Parameters properties The properties for the new cookie object, expressed as key value pairs. Return Value The newly created cookie object. Returns nil if the provided properties are invalid. Discussion See “Constants” (page 732) for more information on the available header field constants and the constraints imposed on the values in the dictionary. Availability Available in iOS 2.0 and later. See Also – initWithProperties: (page 728) Declared in NSHTTPCookie.h requestHeaderFieldsWithCookies: Returns a dictionary of header fields corresponding to a provided array of cookies. + (NSDictionary *)requestHeaderFieldsWithCookies:(NSArray *)cookies NSHTTPCookie Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 725Parameters cookies The cookies from which the header fields are created. Return Value The dictionary of header fields created from the provided cookies. This dictionary can be used to add cookies to a request. Discussion See “Constants” (page 732) for details on the header field keys and values in the returned dictionary. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h Instance Methods comment Returns the receiver's comment string. - (NSString *)comment Return Value The receiver’s comment string or nil if the cookie has no comment. This string is suitable for presentation to the user, explaining the contents and purpose of this cookie. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h commentURL Returns the receiver’s comment URL. - (NSURL *)commentURL NSHTTPCookie Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 726Return Value The receiver’s comment URL or nil if the cookie has none. This value specifies a URL which is suitable for presentation to the user as a link for further information about this cookie. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h domain Returns the domain of the receiver’s cookie. - (NSString *)domain Return Value The domain of the receiver’s cookie. Discussion If the domain does not start with a dot, then the cookie is only sent to the exact host specified by the domain. If the domain does start with a dot, then the cookie is sent to other hosts in that domain as well, subject to certain restrictions. See RFC 2965 for more detail. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h expiresDate Returns the receiver’s expiration date. - (NSDate *)expiresDate Return Value The receiver’s expiration date, or nil if there is no specific expiration date such as in the case of “session-only” cookies. The expiration date is the date when the cookie should be deleted. Availability Available in iOS 2.0 and later. NSHTTPCookie Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 727Declared in NSHTTPCookie.h initWithProperties: Returns an initialized NSHTTPCookie object using the provided properties. - (id)initWithProperties:(NSDictionary *)properties Parameters properties The properties for the new cookie object, expressed as key value pairs. Return Value The initialized cookie object. Returns nil if the provided properties are invalid. Discussion See “Constants” (page 732) for more information on the available header field constants and the constraints imposed on the values in the dictionary. Availability Available in iOS 2.0 and later. See Also + cookieWithProperties: (page 725) Declared in NSHTTPCookie.h isHTTPOnly Returns whether the receiver should only be sent to HTTP servers per RFC 2965. - (BOOL)isHTTPOnly Return Value Returns YES if this cookie should only be sent via HTTP headers, NO otherwise. Discussion Cookies may be marked as HTTP only by a server (or by a javascript). Cookies marked as such must only be sent via HTTP Headers in HTTP requests for URL's that match both the path and domain of the respective cookies. NSHTTPCookie Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 728Important Cookies specified as HTTP only should not be delivered to any javascript applications to prevent cross-site scripting vulnerabilities. Availability Available in iOS 2.2 and later. Declared in NSHTTPCookie.h isSecure Returns whether his cookie should only be sent over secure channels. - (BOOL)isSecure Return Value YES if this cookie should only be sent over secure channels, otherwise NO. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h isSessionOnly Returns whether the receiver should be discarded at the end of the session (regardless of expiration date). - (BOOL)isSessionOnly Return Value YES if the receiver should be discarded at the end of the session (regardless of expiration date), otherwise NO. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h NSHTTPCookie Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 729name Returns the receiver’s name. - (NSString *)name Return Value The receiver's name. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h path Returns the receiver’s path. - (NSString *)path Return Value The receiver's path. Discussion The cookie will be sent with requests for this path in the cookie's domain, and all paths that have this prefix. A path of “/” means the cookie will be sent for all URLs in the domain. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h portList Returns the receiver's port list. - (NSArray *)portList NSHTTPCookie Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 730Return Value The list of ports for the cookie, returned as an array of NSNumber objects containing integers. If the cookie has no port list this method returns nil and the cookie will be sent to any port. Otherwise, the cookie is only sent to ports specified in the port list. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h properties Returns the receiver’s cookie properties. - (NSDictionary *)properties Return Value A dictionary representation of the receiver’s cookie properties. Discussion This dictionary can be used with initWithProperties: (page 728) or cookieWithProperties: (page 725) to create an equivalent NSHTTPCookie object. See initWithProperties: (page 728) for more information on the constraints imposed on the properties dictionary. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h value Returns the receiver’s value. - (NSString *)value Return Value The receiver's value. NSHTTPCookie Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 731Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h version Returns the receiver’s version. - (NSUInteger)version Return Value The receiver's version. Version 0 maps to “old-style” Netscape cookies. Version 1 maps to RFC 2965 cookies. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookie.h Constants HTTP Cookie Property Keys These constants define the supported keys in a dictionary containing cookie attributes. NSHTTPCookie Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 732extern NSString *NSHTTPCookieComment; extern NSString *NSHTTPCookieCommentURL; extern NSString *NSHTTPCookieDiscard; extern NSString *NSHTTPCookieDomain; extern NSString *NSHTTPCookieExpires; extern NSString *NSHTTPCookieMaximumAge; extern NSString *NSHTTPCookieName; extern NSString *NSHTTPCookieOriginURL; extern NSString *NSHTTPCookiePath; extern NSString *NSHTTPCookiePort; extern NSString *NSHTTPCookieSecure; extern NSString *NSHTTPCookieValue; extern NSString *NSHTTPCookieVersion; Constants NSHTTPCookieComment An NSString object containing the comment for the cookie. Only valid for Version 1 cookies and later. This header field is optional. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieCommentURL An NSURL object or NSString object containing the comment URL for the cookie. Only valid for Version 1 cookies or later. This header field is optional. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieDiscard An NSString object stating whether the cookie should be discarded at the end of the session. String value must be either “TRUE” or “FALSE”. This header field is optional. Default is “FALSE”, unless this is cookie is version 1 or greater and a value for NSHTTPCookieMaximumAge is not specified, in which case it is assumed “TRUE”. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieDomain An NSString object containing the domain for the cookie. A value must be specified for either NSHTTPCookieDomain or NSHTTPCookieOriginURL. If this header field is missing the domain is inferred from the value for NSHTTPCookieOriginURL. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookie Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 733NSHTTPCookieExpires An NSDate object or NSString object specifying the expiration date for the cookie. This header field is only used for Version 0 cookies. This header field is optional. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieMaximumAge An NSString object containing an integer value stating how long in seconds the cookie should be kept, at most. Only valid for Version 1 cookies and later. Default is “0”. This field is optional. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieName An NSString object containing the name of the cookie. This field is required. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieOriginURL An NSURL or NSString object containing the URL that set this cookie. A value must be specified for either NSHTTPCookieDomain or NSHTTPCookieOriginURL. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookiePath An NSString object containing the path for the cookie. This field is required if you are using the NSHTTPCookieDomain key instead of the NSHTTPCookieOriginURL key. If you are using the NSHTTPCookieOriginURL key, the path is inferred if it is not provided. The default value is “/”. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookiePort An NSString object containing comma-separated integer values specifying the ports for the cookie. Only valid for Version 1 cookies or later. The default value is an empty string (““). This header field is optional. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookie Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 734NSHTTPCookieSecure An NSString object indicating that the cookie should be transmitted only over secure channels. Providing any value for this key indicates that the cookie should remain secure. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieValue An NSString object containing the value of the cookie. This header field is required. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. NSHTTPCookieVersion An NSString object that specifies the version of the cookie. Must be either “0” or “1”. The default is “0”. This header field is optional. Available in iOS 2.0 and later. Declared in NSHTTPCookie.h. Availability Available in Mac OS X v10.2 with Safari 1.0 installed. Available in Mac OS X v10.2.7 and later. Declared in NSHTTPCookie.h NSHTTPCookie Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 735Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Declared in Foundation/NSHTTPCookieStorage.h Availability Available in iOS 2.0 and later. Companion guide URL Loading System Programming Guide Overview NSHTTPCookieStorage implements a singleton object (shared instance) that manages the shared cookie storage. These cookies are shared among all applications and are kept in sync cross-process. iOS Note Cookies are not shared among applications in iOS. Note Changes made to the cookie accept policy affect all currently running applications using the cookie storage. Tasks Creating and Initializing a Cookie Storage Object – initWithStorageLocation: (page 740) Returns an initialized NSHTTPCookieStorage object with a given file system location to store cookie information on disk. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 736 NSHTTPCookieStorage Class ReferenceGetting the Shared Cookie Storage Object + sharedHTTPCookieStorage (page 738) Returns the shared cookie storage instance. Getting and Setting the Cookie Accept Policy – cookieAcceptPolicy (page 738) Returns the cookie storage’s cookie accept policy. – setCookieAcceptPolicy: (page 741) Sets the cookie accept policy of the cookie storage. Adding and Removing Cookies – deleteCookie: (page 740) Deletes the specified cookie from the cookie storage. – setCookie: (page 740) Stores a specified cookie in the cookie storage if the cookie accept policy permits. – setCookies:forURL:mainDocumentURL: (page 741) Adds an array of cookies to the receiver if the receiver’s cookie acceptance policy permits. Retrieving Cookies – cookies (page 738) Returns the cookie storage’s cookies. – cookiesForURL: (page 739) Returns all the cookie storage’s cookies that are sent to a specified URL. – sortedCookiesUsingDescriptors: (page 742) Returns all of the cookie storage’s cookies, sorted according to a given set of sort descriptors. NSHTTPCookieStorage Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 737Class Methods sharedHTTPCookieStorage Returns the shared cookie storage instance. + (NSHTTPCookieStorage *)sharedHTTPCookieStorage Return Value The shared cookie storage instance. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h Instance Methods cookieAcceptPolicy Returns the cookie storage’s cookie accept policy. - (NSHTTPCookieAcceptPolicy)cookieAcceptPolicy Return Value The cookie storage’s cookie accept policy. The default cookie accept policy is NSHTTPCookieAcceptPolicyAlways. Availability Available in iOS 2.0 and later. See Also – setCookieAcceptPolicy: (page 741) Declared in NSHTTPCookieStorage.h cookies Returns the cookie storage’s cookies. NSHTTPCookieStorage Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 738- (NSArray *)cookies Return Value An array containing all of the cookie storage’s cookies. Availability Available in iOS 2.0 and later. Discussion If you want to sort the cookie storage’s cookies, you should use the sortedCookiesUsingDescriptors: (page 742) method instead of sorting the result of this method. See Also – cookiesForURL: (page 739) Declared in NSHTTPCookieStorage.h cookiesForURL: Returns all the cookie storage’s cookies that are sent to a specified URL. - (NSArray *)cookiesForURL:(NSURL *)theURL Parameters theURL The URL to filter on. Return Value An array of cookies whose URL matches the provided URL. Discussion An application can use NSHTTPCookie method requestHeaderFieldsWithCookies: (page 725) to turn this array into a set of header fields to add to an NSMutableURLRequest object. Availability Available in iOS 2.0 and later. See Also – cookies (page 738) Declared in NSHTTPCookieStorage.h NSHTTPCookieStorage Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 739deleteCookie: Deletes the specified cookie from the cookie storage. - (void)deleteCookie:(NSHTTPCookie *)aCookie Parameters aCookie The cookie to delete. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h initWithStorageLocation: ReturnsaninitializedNSHTTPCookieStorageobjectwithagivenfilesystemlocationtostorecookieinformation on disk. (Available in iOS 4.0 through iOS 4.3.) - (id)initWithStorageLocation:(NSURL *)storageFileURL Parameters storageFileURL A file:// URL that indicates the file to use for cookie storage. Return Value An initialized NSHTTPCookieStorage object that stores its cookie information at storageFileURL. Availability Available in iOS 4.0 through iOS 4.3. Declared in NSHTTPCookieStorage.h setCookie: Stores a specified cookie in the cookie storage if the cookie accept policy permits. - (void)setCookie:(NSHTTPCookie *)aCookie NSHTTPCookieStorage Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 740Parameters aCookie The cookie to store. Discussion The cookie replaces an existing cookie with the same name, domain, and path, if one exists in the cookie storage. This method accepts the cookie only if the receiver’s cookie accept policy is NSHTTPCookieAcceptPolicyAlways or NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain. The cookie is ignored if the receiver’s cookie accept policy is NSHTTPCookieAcceptPolicyNever. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h setCookieAcceptPolicy: Sets the cookie accept policy of the cookie storage. - (void)setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)aPolicy Parameters aPolicy The new cookie accept policy. Discussion The default cookie accept policy is NSHTTPCookieAcceptPolicyAlways. Changing the cookie policy affects all currently running applications using the cookie storage. Availability Available in iOS 2.0 and later. See Also – cookieAcceptPolicy (page 738) Declared in NSHTTPCookieStorage.h setCookies:forURL:mainDocumentURL: Adds an array of cookies to the receiver if the receiver’s cookie acceptance policy permits. NSHTTPCookieStorage Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 741- (void)setCookies:(NSArray *)cookies forURL:(NSURL *)theURL mainDocumentURL:(NSURL *)mainDocumentURL Parameters cookies The cookies to add. theURL The URL associated with the added cookies. mainDocumentURL The URL of the main HTML document for the top-level frame, if known. Can be nil. This URL is used to determine if the cookie should be accepted if the cookie accept policy is NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain. Discussion The cookies will replace existing cookies with the same name, domain, and path, if one exists in the cookie storage. The cookie will be ignored if the receiver's cookie accept policy is NSHTTPCookieAcceptPolicyNever. To store cookies from a set of response headers, an application can use cookiesWithResponseHeaderFields:forURL: (page 724) passing a header field dictionary and then use this method to store the resulting cookies in accordance with the receiver’s cookie acceptance policy. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h sortedCookiesUsingDescriptors: Returns all of the cookie storage’s cookies, sorted according to a given set of sort descriptors. - (NSArray *)sortedCookiesUsingDescriptors:(NSArray *)sortOrder Parameters sortOrder The sort descriptors to use for sorting, as an array of NSSortDescriptor objects. Return Value The cookie storage’s cookies, sorted according to sortOrder, as an array of NSHTTPCookie objects. NSHTTPCookieStorage Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 742Availability Available in iOS 5.0 and later. Declared in NSHTTPCookieStorage.h Constants NSHTTPCookieAcceptPolicy NSHTTPCookieAcceptPolicy specifies the cookie acceptance policies implemented by the NSHTTPCookieStorage class. typedef enum { NSHTTPCookieAcceptPolicyAlways, NSHTTPCookieAcceptPolicyNever, NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain } NSHTTPCookieAcceptPolicy; Constants NSHTTPCookieAcceptPolicyAlways Accept all cookies. This is the default cookie accept policy. Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h. NSHTTPCookieAcceptPolicyNever Reject all cookies. Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h. NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain Accept cookies only from the main document domain. Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h NSHTTPCookieStorage Class Reference Constants 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 743Notifications NSHTTPCookieManagerCookiesChangedNotification This notification is posted when the cookies stored in the NSHTTPCookieStorage instance have changed. In Mac OS X, cookies are shared among applications, meaning this notification can be sent in response to another application’s actions. Cookies are not shared among applications in iOS. The notification object is the NSHTTPCookieStorage instance. This notification does not contain a userInfo dictionary. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h NSHTTPCookieManagerAcceptPolicyChangedNotification This notification is posted when the acceptance policy of the NSHTTPCookieStorage instance has changed. In Mac OS X, cookies are shared among applications, meaning this notification can be sent in response to another application’s actions. Cookies are not shared among applications in iOS. The notification object is the NSHTTPCookieStorage instance. This notification does not contain a userInfo dictionary. Availability Available in iOS 2.0 and later. Declared in NSHTTPCookieStorage.h NSHTTPCookieStorage Class Reference Notifications 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 744Inherits from NSURLResponse : NSObject Conforms to NSCoding (NSURLResponse) NSCopying (NSURLResponse) NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Declared in Foundation/NSURLResponse.h Availability Available in iOS 2.0 and later. Companion guide URL Loading System Programming Guide Related sample code SeismicXML SimpleURLConnections URLCache Overview An NSHTTPURLResponse object represents a response to an HTTP URL load request. It’s a subclass of NSURLResponse that provides methods for accessing information specific to HTTP protocol responses. Adopted Protocols NSCoding – encodeWithCoder: (page 1999) – initWithCoder: (page 1999) NSCopying – copyWithZone: (page 2002) 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 745 NSHTTPURLResponse Class ReferenceTasks Getting HTTP Response Headers – allHeaderFields (page 747) Returns all the HTTP header fields of the receiver. Getting Response Status Code + localizedStringForStatusCode: (page 746) Returns a localized string corresponding to a specified HTTP status code. – statusCode (page 747) Returns the receiver’s HTTP status code. Class Methods localizedStringForStatusCode: Returns a localized string corresponding to a specified HTTP status code. + (NSString *)localizedStringForStatusCode:(NSInteger)statusCode Parameters statusCode The HTTP status code. Return Value A localized string suitable for displaying to users that describes the specified status code. Availability Available in iOS 2.0 and later. See Also – statusCode (page 747) Declared in NSURLResponse.h NSHTTPURLResponse Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 746Instance Methods allHeaderFields Returns all the HTTP header fields of the receiver. - (NSDictionary *)allHeaderFields Return Value A dictionary containing all the HTTP header fields of the receiver. By examining this dictionary clients can see the “raw” header information returned by the HTTP server. Availability Available in iOS 2.0 and later. Declared in NSURLResponse.h statusCode Returns the receiver’s HTTP status code. - (NSInteger)statusCode Return Value The receiver’s HTTP status code. Availability Available in iOS 2.0 and later. See Also + localizedStringForStatusCode: (page 746) Related Sample Code SeismicXML SimpleURLConnections Declared in NSURLResponse.h NSHTTPURLResponse Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 747Inherits from NSObject Conforms to NSCoding NSCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSIndexPath.h Companion guide Collections Programming Topics Related sample code BonjourWeb CoreDataBooks iPhoneCoreDataRecipes LazyTableImages TableViewSuite Overview The NSIndexPath class represents the path to a specific node in a tree of nested array collections. This path is known as an index path. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 748 NSIndexPath Class ReferenceEach index in an index path represents the index into an array of children from one node in the tree to another, deeper, node. For example, the index path 1.4.3.2 specifies the path shown in Figure 38-1. Figure 38-1 Index path 1.4.3.2 Array 3 0 1 2 3 4 5 6 7 8 9 10 Array 2 0 1 2 3 4 5 6 7 8 9 Array 1 0 1 2 3 4 5 6 7 Array 0 0 1 2 3 4 5 6 Note iOS adds programming interfaces to the NSIndexPath class of the Foundation framework to facilitate the identification of rows and sections in UITableView objects. The API consists of a class method and two properties. The indexPathForRow:inSection: method creates an NSIndexPath object from row and section index numbers. The properties return the row index number and the section index number from such objects. See NSIndexPath UIKit Additions for details. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSIndexPath Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 749Tasks Creating Index Paths + indexPathWithIndex: (page 751) Creates an one-node index path. + indexPathWithIndexes:length: (page 751) Creates an index path with one or more nodes. – initWithIndex: (page 754) Initializes an allocated NSIndexPath (page 748) object with a one-node index path. – initWithIndexes:length: (page 755) Initializes an allocated NSIndexPath (page 748) object with an index path of a specific length. Querying Index Paths – indexAtPosition: (page 753) Provides the index at a particular node in the index path. – indexPathByAddingIndex: (page 753) Provides an index path containing the indexes in the receiving index path and another index. – indexPathByRemovingLastIndex (page 754) Provides an index path with the indexes in the receiving index path, excluding the last one. – length (page 756) Provides the number of indexes in the index path. – getIndexes: (page 752) Copies the objects contained in the index path into indexes. Comparing Index Paths – compare: (page 752) Indicates the depth-first traversal order of the receiving index path and another index path. NSIndexPath Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 750Class Methods indexPathWithIndex: Creates an one-node index path. + (id)indexPathWithIndex:(NSUInteger)index Parameters index Index of the item in node 0 to point to. Return Value One-node index path with index. Availability Available in iOS 2.0 and later. See Also – initWithIndex: (page 754) Declared in NSIndexPath.h indexPathWithIndexes:length: Creates an index path with one or more nodes. + (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length Parameters indexes Array of indexes to make up the index path. length Number of nodes to include in the index path. Return Value Index path with indexes up to length. Availability Available in iOS 2.0 and later. NSIndexPath Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 751See Also – initWithIndexes:length: (page 755) Related Sample Code BonjourWeb Declared in NSIndexPath.h Instance Methods compare: Indicates the depth-first traversal order of the receiving index path and another index path. - (NSComparisonResult)compare:(NSIndexPath *)indexPath Parameters indexPath Index path to compare. This value must not be nil. If the value is nil, the behavior is undefined. Return Value The depth-first traversal ordering of the receiving index path and indexPath. ● NSOrderedAscending: The receiving index path comes before indexPath. ● NSOrderedDescending: The receiving index path comes after indexPath. ● NSOrderedSame: The receiving index path and indexPath are the same index path. Availability Available in iOS 2.0 and later. Declared in NSIndexPath.h getIndexes: Copies the objects contained in the index path into indexes. - (void)getIndexes:(NSUInteger *)indexes NSIndexPath Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 752Parameters indexes Pointer to a C array of objects of size at least the length of the index path. On return, the index path’s indexes. Discussion It is the developer’s responsibility to allocate the memory for the C array. Availability Available in iOS 2.0 and later. Declared in NSIndexPath.h indexAtPosition: Provides the index at a particular node in the index path. - (NSUInteger)indexAtPosition:(NSUInteger)node Parameters node Index value of the desired node. Node numbering starts at zero. Return Value The index value at node or NSNotFound (page 2267) if the node is outside the range of the index path. Availability Available in iOS 2.0 and later. Declared in NSIndexPath.h indexPathByAddingIndex: Provides an index path containing the indexes in the receiving index path and another index. - (NSIndexPath *)indexPathByAddingIndex:(NSUInteger)index Parameters index Index to append to the index path’s indexes. NSIndexPath Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 753Return Value New NSIndexPath (page 748) object containing the receiving index path’s indexes and index. Availability Available in iOS 2.0 and later. See Also – indexPathByRemovingLastIndex (page 754) Declared in NSIndexPath.h indexPathByRemovingLastIndex Provides an index path with the indexes in the receiving index path, excluding the last one. - (NSIndexPath *)indexPathByRemovingLastIndex Return Value New index path with the receiving index path’s indexes, excluding the last one. Discussion Returns an empty NSIndexPath instance if the receiving index path’s length is 1 or less. Special Considerations On Mac OS X 10.4 this method returns nil when the length of the receiving index path is 1 or less. On iOS and Mac OS X 10.5 and later this method will never return nil. Availability Available in iOS 2.0 and later. See Also – indexPathByAddingIndex: (page 753) Declared in NSIndexPath.h initWithIndex: Initializes an allocated NSIndexPath (page 748) object with a one-node index path. - (id)initWithIndex:(NSUInteger)index NSIndexPath Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 754Parameters index Index of the item in node 0 to point to. Return Value Initialized NSIndexPath (page 748) object representing a one-node index path with index. Availability Available in iOS 2.0 and later. See Also + indexPathWithIndex: (page 751) Declared in NSIndexPath.h initWithIndexes:length: Initializes an allocated NSIndexPath (page 748) object with an index path of a specific length. - (id)initWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length Parameters indexes Array of indexes to make up the index path. length Number of nodes to include in the index path. Return Value Initialized NSIndexPath (page 748) object with indexes up to length. Availability Available in iOS 2.0 and later. See Also + indexPathWithIndexes:length: (page 751) Declared in NSIndexPath.h NSIndexPath Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 755length Provides the number of indexes in the index path. - (NSUInteger)length Return Value Number of indexes in the index path. Availability Available in iOS 2.0 and later. Declared in NSIndexPath.h NSIndexPath Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 756Inherits from NSObject Conforms to NSCoding NSCopying NSMutableCopying NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSIndexSet.h Companion guide Collections Programming Topics Related sample code BonjourWeb CoreDataBooks iPhoneCoreDataRecipes Overview The NSIndexSet class represents an immutable collection of unique unsigned integers, known as indexes because of the way they are used. This collection is referred to as an index set. You use index sets in your code to store indexes into some other data structure. For example, given an NSArray object, you could use an index set to identify a subset of objects in that array. You should not use index sets to store an arbitrary collection of integer values because index sets store indexes as sorted ranges. This makes them more efficient than storing a collection of individual integers. It also means that each index value can only appear once in the index set. The designated initializers of the NSIndexSet class are: initWithIndexesInRange: (page 777) and initWithIndexSet: (page 778). You must not subclass the NSIndexSet class. 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 757 NSIndexSet Class ReferenceThe mutable subclass of NSIndexSet is NSMutableIndexSet. Adopted Protocols NSCoding encodeWithCoder: (page 1999) initWithCoder: (page 1999) NSCopying copyWithZone: (page 2002) NSMutableCopying mutableCopyWithZone: (page 2103) Tasks Creating Index Sets + indexSet (page 761) Creates an empty index set. + indexSetWithIndex: (page 761) Creates an index set with an index. + indexSetWithIndexesInRange: (page 762) Creates an index set with an index range. – init (page 776) Initializes an allocated NSIndexSet (page 757) object. – initWithIndex: (page 777) Initializes an allocated NSIndexSet (page 757) object with an index. – initWithIndexesInRange: (page 777) Initializes an allocated NSIndexSet (page 757) object with an index range. – initWithIndexSet: (page 778) Initializes an allocated NSIndexSet (page 757) object with an index set. NSIndexSet Class Reference Adopted Protocols 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 758Querying Index Sets – containsIndex: (page 762) Indicates whether the index set contains a specific index. – containsIndexes: (page 763) Indicates whether the receiving index set contains a superset of the indexes in another index set. – containsIndexesInRange: (page 763) Indicates whether the index set contains the indexes represented by an index range. – intersectsIndexesInRange: (page 778) Indicates whether the index set contains any of the indexes in a range. – count (page 764) Returns the number of indexes in the index set. – countOfIndexesInRange: (page 764) Returns the number of indexes in the index set that are members of a given range. – indexPassingTest: (page 774) Returns the index of the first object that passes the predicate Block test. – indexesPassingTest: (page 769) Returns an NSIndexSet containing the receiving index set’s objects that pass the Block test. – indexWithOptions:passingTest: (page 775) Returns the index of the first object that passes the predicate Block test using the specified enumeration options. – indexesWithOptions:passingTest: (page 770) Returns an NSIndexSet containing the receiving index set’s objects that pass the Block test using the specified enumeration options. – indexInRange:options:passingTest: (page 772) Returns the index of the first object in the specified range that passes the predicate Block test. – indexesInRange:options:passingTest: (page 768) Returns an NSIndexSet containing the receiving index set’s objects in the specified range that pass the Block test. Comparing Index Sets – isEqualToIndexSet: (page 779) Indicates whether the indexes in the receiving index set are the same indexes contained in another index set. NSIndexSet Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 759Getting Indexes – firstIndex (page 767) Returns either the first index in the index set or the not-found indicator. – lastIndex (page 779) Returns either the last index in the index set or the not-found indicator. – indexLessThanIndex: (page 773) Returns either the closest index in the index set that is less than a specific index or the not-found indicator. – indexLessThanOrEqualToIndex: (page 774) Returns either the closest index in the index set that is less than or equal to a specific index or the not-found indicator. – indexGreaterThanOrEqualToIndex: (page 772) Returns either the closest index in the index set that is greater than or equal to a specific index or the not-found indicator. – indexGreaterThanIndex: (page 771) Returns either the closest index in the index set that is greater than a specific index or the not-found indicator. – getIndexes:maxCount:inIndexRange: (page 767) The index set fills an index buffer with the indexes contained both in the index set and in an index range, returning the number of indexes copied. Enumerating Indexes – enumerateIndexesUsingBlock: (page 766) Executes a given Block using each object in the index set. – enumerateIndexesWithOptions:usingBlock: (page 766) Executes a given Block over the index set’s indexes, using the specified enumeration options. – enumerateIndexesInRange:options:usingBlock: (page 765) Executes a given Block using the indexes in the specified range, using the specified enumeration options. NSIndexSet Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 760Class Methods indexSet Creates an empty index set. + (id)indexSet Return Value NSIndexSet (page 757) object with no members. Availability Available in iOS 2.0 and later. See Also – init (page 776) Declared in NSIndexSet.h indexSetWithIndex: Creates an index set with an index. + (id)indexSetWithIndex:(NSUInteger)index Parameters index An index. Return Value NSIndexSet (page 757) object containing index. Availability Available in iOS 2.0 and later. See Also – initWithIndex: (page 777) Related Sample Code BonjourWeb CoreDataBooks iPhoneCoreDataRecipes NSIndexSet Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 761Declared in NSIndexSet.h indexSetWithIndexesInRange: Creates an index set with an index range. + (id)indexSetWithIndexesInRange:(NSRange)indexRange Parameters indexRange An index range. Return Value NSIndexSet (page 757) object containing indexRange. Availability Available in iOS 2.0 and later. See Also – initWithIndexesInRange: (page 777) Declared in NSIndexSet.h Instance Methods containsIndex: Indicates whether the index set contains a specific index. - (BOOL)containsIndex:(NSUInteger)index Parameters index Index being inquired about. Return Value YES when the index set contains index, NO otherwise. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 762Availability Available in iOS 2.0 and later. See Also – containsIndexes: (page 763) – containsIndexesInRange: (page 763) Declared in NSIndexSet.h containsIndexes: Indicates whether the receiving index set contains a superset of the indexes in another index set. - (BOOL)containsIndexes:(NSIndexSet *)indexSet Parameters indexSet Index set being inquired about. Return Value YES when the receiving index set contains a superset of the indexes in indexSet, NO otherwise. Availability Available in iOS 2.0 and later. See Also – containsIndex: (page 762) – containsIndexesInRange: (page 763) Declared in NSIndexSet.h containsIndexesInRange: Indicates whether the index set contains the indexes represented by an index range. - (BOOL)containsIndexesInRange:(NSRange)indexRange Parameters indexRange The index range being inquired about. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 763Return Value YES when the index set contains the indexes in indexRange, NO otherwise. Availability Available in iOS 2.0 and later. See Also – containsIndex: (page 762) – containsIndexes: (page 763) – intersectsIndexesInRange: (page 778) Declared in NSIndexSet.h count Returns the number of indexes in the index set. - (NSUInteger)count Return Value Number of indexes in the index set. Availability Available in iOS 2.0 and later. See Also – countOfIndexesInRange: (page 764) Declared in NSIndexSet.h countOfIndexesInRange: Returns the number of indexes in the index set that are members of a given range. - (NSUInteger)countOfIndexesInRange:(NSRange)indexRange Parameters indexRange Index range being inquired about. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 764Return Value Number of indexes in the index set that are members of indexRange. Availability Available in iOS 2.0 and later. See Also – count (page 764) Declared in NSIndexSet.h enumerateIndexesInRange:options:usingBlock: Executes a given Block using the indexes in the specified range, using the specified enumeration options. - (void)enumerateIndexesInRange:(NSRange)range options:(NSEnumerationOptions)opts usingBlock:(void (^)(NSUInteger idx, BOOL *stop))block Parameters range Index to enumerate. 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). See NSEnumerationOptions (page 2267) for the supported values. block The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. Availability Available in iOS 4.0 and later. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 765Declared in NSIndexSet.h enumerateIndexesUsingBlock: Executes a given Block using each object in the index set. - (void)enumerateIndexesUsingBlock:(void (^)(NSUInteger idx, BOOL *stop))block Parameters block The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h enumerateIndexesWithOptions:usingBlock: Executes a given Block over the index set’s indexes, using the specified enumeration options. - (void)enumerateIndexesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(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). See NSEnumerationOptions (page 2267) for the supported values. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 766block The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h firstIndex Returns either the first index in the index set or the not-found indicator. - (NSUInteger)firstIndex Return Value First index in the index set or NSNotFound (page 2267) when the index set is empty. Availability Available in iOS 2.0 and later. See Also – lastIndex (page 779) Declared in NSIndexSet.h getIndexes:maxCount:inIndexRange: The index set fills an index buffer with the indexes contained both in the index set and in an index range, returning the number of indexes copied. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 767- (NSUInteger)getIndexes:(NSUInteger *)indexBuffer maxCount:(NSUInteger)bufferSize inIndexRange:(NSRangePointer)indexRangePointer Parameters indexBuffer Index buffer to fill. bufferSize Maximum size of indexBuffer. indexRange Index range to compare with indexes in the index set; nil represents all the indexes in the index set. Indexes in the index range and in the index set are copied to indexBuffer. On output, the range of indexes not copied to indexBuffer. Return Value Number of indexes placed in indexBuffer. Discussion You are responsible for allocating the memory required for indexBuffer and for releasing it later. Suppose you have an index set with contiguous indexes from 1 to 100. If you use this method to request a range of (1, 100)—which represents the set of indexes 1 through 100—and specify a buffer size of 20, this method returns 20 indexes—1 through 20—in indexBuffer and sets indexRange to (21, 80)—which represents the indexes 21 through 100. Use this method to retrieve entries quickly and efficiently from an index set. You can call this method repeatedly to retrieve blocks of index values and then process them. When doing so, use the return value and indexRange to determine when you have finished processing the desired indexes. When the return value is less than bufferSize, you have reached the end of the range. Availability Available in iOS 2.0 and later. Declared in NSIndexSet.h indexesInRange:options:passingTest: Returns an NSIndexSet containing the receiving index set’s objects in the specified range that pass the Block test. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 768- (NSIndexSet *)indexesInRange:(NSRange)range options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate Parameters range The range of indexes to test. 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). See NSEnumerationOptions (page 2267) for the supported values. predicate The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. The Block returns a Boolean value that indicates whether obj passed the test. Return Value An NSIndexSet containing the indexes of the receiving index set that passed the predicate Block test. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h indexesPassingTest: Returns an NSIndexSet containing the receiving index set’s objects that pass the Block test. - (NSIndexSet *)indexesPassingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 769Parameters predicate The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. The Block returns a Boolean value that indicates whether obj passed the test. Return Value An NSIndexSet containing the indexes of the receiving index set that passed the predicate Block test. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h indexesWithOptions:passingTest: Returns an NSIndexSet containing the receiving index set’s objects that pass the Block test using the specified enumeration options. - (NSIndexSet *)indexesWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate 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). See NSEnumerationOptions (page 2267) for the supported values. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 770predicate The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. The Block returns a Boolean value that indicates whether obj passed the test. Return Value An NSIndexSet containing the indexes of the receiving index set that passed the predicate Block test. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h indexGreaterThanIndex: Returns either the closest index in the index set that is greater than a specific index or the not-found indicator. - (NSUInteger)indexGreaterThanIndex:(NSUInteger)index Parameters index Index being inquired about. Return Value Closest index in the index set greater than index; NSNotFound (page 2267) when the index set contains no qualifying index. Availability Available in iOS 2.0 and later. See Also – indexLessThanIndex: (page 773) – indexGreaterThanOrEqualToIndex: (page 772) NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 771– indexLessThanOrEqualToIndex: (page 774) Declared in NSIndexSet.h indexGreaterThanOrEqualToIndex: Returns either the closest index in the index set that is greater than or equal to a specific index or the not-found indicator. - (NSUInteger)indexGreaterThanOrEqualToIndex:(NSUInteger)index Parameters index Index being inquired about. Return Value Closest index in the index set greater than or equal to index; NSNotFound (page 2267) when the index set contains no qualifying index. Availability Available in iOS 2.0 and later. See Also – indexGreaterThanIndex: (page 771) – indexLessThanIndex: (page 773) – indexLessThanOrEqualToIndex: (page 774) Declared in NSIndexSet.h indexInRange:options:passingTest: Returns the index of the first object in the specified range that passes the predicate Block test. - (NSUInteger)indexInRange:(NSRange)range options:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate Parameters range The range of indexes to test. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 772opts A bitmask that specifies the options for the enumeration (whether it should be performed concurrently and whether it should be performed in reverse order). See NSEnumerationOptions (page 2267) for the supported values. predicate The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The index of the first object that passes the predicate test. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h indexLessThanIndex: Returns either the closest index in the index set that is less than a specific index or the not-found indicator. - (NSUInteger)indexLessThanIndex:(NSUInteger)index Parameters index Index being inquired about. Return Value Closest index in the index set less than index; NSNotFound (page 2267) when the index set contains no qualifying index. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 773Availability Available in iOS 2.0 and later. See Also – indexGreaterThanIndex: (page 771) – indexGreaterThanOrEqualToIndex: (page 772) – indexLessThanOrEqualToIndex: (page 774) Declared in NSIndexSet.h indexLessThanOrEqualToIndex: Returns either the closest index in the index set that is less than or equal to a specific index or the not-found indicator. - (NSUInteger)indexLessThanOrEqualToIndex:(NSUInteger)index Parameters index Index being inquired about. Return Value Closest index in the index set less than or equal to index; NSNotFound (page 2267) when the index set contains no qualifying index. Availability Available in iOS 2.0 and later. See Also – indexGreaterThanIndex: (page 771) – indexLessThanIndex: (page 773) – indexGreaterThanOrEqualToIndex: (page 772) Declared in NSIndexSet.h indexPassingTest: Returns the index of the first object that passes the predicate Block test. - (NSUInteger)indexPassingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 774Parameters predicate The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The index of the first object that passes the predicate test. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h indexWithOptions:passingTest: Returns the index of the first object that passes the predicate Block test using the specified enumeration options. - (NSUInteger)indexWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(NSUInteger idx, BOOL *stop))predicate 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). See NSEnumerationOptions (page 2267) for the supported values. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 775predicate The Block to apply to elements in the set. The Block takes two arguments: idx The index of the object. stop A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block. The Block returns a Boolean value that indicates whether obj passed the test. Return Value The index of the first object that passes the predicate test. Availability Available in iOS 4.0 and later. Declared in NSIndexSet.h init Initializes an allocated NSIndexSet (page 757) object. - (id)init Return Value Initialized, empty NSIndexSet (page 757) object. Availability Available in iOS 2.0 and later. See Also + indexSet (page 761) Declared in NSIndexSet.h NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 776initWithIndex: Initializes an allocated NSIndexSet (page 757) object with an index. - (id)initWithIndex:(NSUInteger)index Parameters index An index. Return Value Initialized NSIndexSet (page 757) object with index. Availability Available in iOS 2.0 and later. See Also + indexSetWithIndex: (page 761) Declared in NSIndexSet.h initWithIndexesInRange: Initializes an allocated NSIndexSet (page 757) object with an index range. - (id)initWithIndexesInRange:(NSRange)indexRange Parameters indexRange An index range. Must include only indexes representable as unsigned integers. Return Value Initialized NSIndexSet (page 757) object with indexRange. Discussion This method raises an NSRangeException (page 2292) when indexRange would add an index that exceeds the maximum allowed value for unsigned integers. This method is a designated initializer for NSIndexSet (page 757). Availability Available in iOS 2.0 and later. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 777See Also + indexSetWithIndexesInRange: (page 762) Declared in NSIndexSet.h initWithIndexSet: Initializes an allocated NSIndexSet (page 757) object with an index set. - (id)initWithIndexSet:(NSIndexSet *)indexSet Parameters indexSet An index set. Return Value Initialized NSIndexSet (page 757) object with indexSet. Discussion This method is a designated initializer for NSIndexSet (page 757). Availability Available in iOS 2.0 and later. Declared in NSIndexSet.h intersectsIndexesInRange: Indicates whether the index set contains any of the indexes in a range. - (BOOL)intersectsIndexesInRange:(NSRange)indexRange Parameters indexRange Index range being inquired about. Return Value YES when the index set contains one or more of the indexes in indexRange, NO otherwise. NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 778Availability Available in iOS 2.0 and later. See Also – containsIndexesInRange: (page 763) Declared in NSIndexSet.h isEqualToIndexSet: Indicates whether the indexes in the receiving index set are the same indexes contained in another index set. - (BOOL)isEqualToIndexSet:(NSIndexSet *)indexSet Parameters indexSet Index set being inquired about. Return Value YES when the indexes in the receiving index set are the same indexes indexSet contains, NO otherwise. Availability Available in iOS 2.0 and later. Declared in NSIndexSet.h lastIndex Returns either the last index in the index set or the not-found indicator. - (NSUInteger)lastIndex Return Value Last index in the index set or NSNotFound (page 2267) when the index set is empty. Availability Available in iOS 2.0 and later. See Also – firstIndex (page 767) NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 779Declared in NSIndexSet.h NSIndexSet Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 780Inherits from NSStream : NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSStream.h Companion guide Stream Programming Guide Related sample code CryptoExercise SimpleFTPSample SimpleNetworkStreams SimpleURLConnections Overview NSInputStream is a subclass of NSStream that provides read-only stream functionality. NSInputStream is “toll-free bridged” with its Core Foundation counterpart, CFReadStreamRef. For more information on toll-free bridging, see “Toll-Free Bridging”. Subclassing Notes NSInputStream is a concrete subclass of NSStream that gives you standard read-only access to stream data. Although NSInputStream is probably sufficient for most situations requiring access to stream data, you can create a subclass of NSInputStream if you want more specialized behavior (for example, you want to record statistics on the data in a stream). 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 781 NSInputStream Class ReferenceMethods to Override To create a subclass of NSInputStream you may have to implement initializers for the type of stream data supported and suitably re-implement existing initializers. You must also provide complete implementations of the following methods: ● read:maxLength: (page 787) From the current read index, take up to the number of bytes specified in the second parameter from the stream and place them in the client-supplied buffer (first parameter). The buffer must be of the size specified by the second parameter. Return the actual number of bytes placed in the buffer; if there is nothing left in the stream, return 0. Reset the index into the stream for the next read operation. ● getBuffer:length: (page 785) Return in 0(1) a pointer to the subclass-allocated buffer (first parameter). Return by reference in the second parameter the number of bytes actually put into the buffer. The buffer’s contents are valid only until the next stream operation. Return NO if you cannot access data in the buffer; otherwise, return YES. If this method is not appropriate for your type of stream, you may return NO. ● hasBytesAvailable (page 785) Return YES if there is more data to read in the stream, NO if there is not. If you want to be semantically compatible with NSInputStream, return YES if a read must be attempted to determine if bytes are available. Tasks Creating Streams + inputStreamWithData: (page 783) Creates and returns an initialized NSInputStream object for reading from a given NSData object. + inputStreamWithFileAtPath: (page 784) Creates and returns an initialized NSInputStream object that reads data from the file at a given path. + inputStreamWithURL: (page 784) Creates and returns an initialized NSInputStream object that reads data from the file at a given URL. – initWithData: (page 786) Initializes and returns an NSInputStream object for reading from a given NSData object. – initWithFileAtPath: (page 786) Initializes and returns an NSInputStream object that reads data from the file at a given path. NSInputStream Class Reference Tasks 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 782– initWithURL: (page 787) Initializes and returns an NSInputStream object that reads data from the file at a given URL. Using Streams – read:maxLength: (page 787) Reads up to a given number of bytes into a given buffer. – getBuffer:length: (page 785) Returns by reference a pointer to a read buffer and, by reference, the number of bytes available, and returns a Boolean value that indicates whether the buffer is available. – hasBytesAvailable (page 785) Returns a Boolean value that indicates whether the receiver has bytes available to read. Class Methods inputStreamWithData: Creates and returns an initialized NSInputStream object for reading from a given NSData object. + (id)inputStreamWithData:(NSData *)data Parameters data The data object from which to read. The contents of data are copied. Return Value An initialized NSInputStream object for reading from data. If data is not an NSData object, this method returns nil. Availability Available in iOS 2.0 and later. See Also + inputStreamWithFileAtPath: (page 784) – initWithData: (page 786) Declared in NSStream.h NSInputStream Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 783inputStreamWithFileAtPath: Creates and returns an initialized NSInputStream object that reads data from the file at a given path. + (id)inputStreamWithFileAtPath:(NSString *)path Parameters path The path to the file. Return Value An initialized NSInputStream object that reads data from the file at path. If the file specified by path doesn’t exist or is unreadable, returns nil. Availability Available in iOS 2.0 and later. See Also + inputStreamWithData: (page 783) – initWithFileAtPath: (page 786) – initWithURL: (page 787) Related Sample Code SimpleFTPSample SimpleNetworkStreams SimpleURLConnections Declared in NSStream.h inputStreamWithURL: Creates and returns an initialized NSInputStream object that reads data from the file at a given URL. + (id)inputStreamWithURL:(NSURL *)url Parameters url The URL to the file. Return Value An initialized NSInputStream object that reads data from the URL at url. If the file specified by url doesn’t exist or is unreadable, returns nil. NSInputStream Class Reference Class Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 784Availability Available in iOS 4.0 and later. See Also + inputStreamWithData: (page 783) Declared in NSStream.h Instance Methods getBuffer:length: Returns by reference a pointer to a read buffer and, by reference, the number of bytes available, and returns a Boolean value that indicates whether the buffer is available. - (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len Parameters buffer Upon return, contains a pointer to a read buffer. The buffer is only valid until the next stream operation is performed. len Upon return, contains the number of bytes available. Return Value YES if the buffer is available, otherwise NO. Subclasses of NSInputStream may return NO if this operation is not appropriate for the stream type. Availability Available in iOS 2.0 and later. Declared in NSStream.h hasBytesAvailable Returns a Boolean value that indicates whether the receiver has bytes available to read. - (BOOL)hasBytesAvailable NSInputStream Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 785Return Value YES if the receiver has bytes available to read, otherwise NO. May also return YES if a read must be attempted in order to determine the availability of bytes. Availability Available in iOS 2.0 and later. Declared in NSStream.h initWithData: Initializes and returns an NSInputStream object for reading from a given NSData object. - (id)initWithData:(NSData *)data Parameters data The data object from which to read. The contents of data are copied. Return Value An initialized NSInputStream object for reading from data. Availability Available in iOS 2.0 and later. See Also – initWithFileAtPath: (page 786) + inputStreamWithData: (page 783) Declared in NSStream.h initWithFileAtPath: Initializes and returns an NSInputStream object that reads data from the file at a given path. - (id)initWithFileAtPath:(NSString *)path Parameters path The path to the file. NSInputStream Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 786Return Value An initialized NSInputStream object that reads data from the file at path. If the file specified by path doesn’t exist or is unreadable, returns nil. Availability Available in iOS 2.0 and later. See Also – initWithData: (page 786) + inputStreamWithFileAtPath: (page 784) + inputStreamWithURL: (page 784) Declared in NSStream.h initWithURL: Initializes and returns an NSInputStream object that reads data from the file at a given URL. - (id)initWithURL:(NSURL *)url Parameters url The URL to the file. Return Value An initialized NSInputStream object that reads data from the file at url. If the file specified by url doesn’t exist or is unreadable, returns nil. Availability Available in iOS 4.0 and later. See Also – initWithData: (page 786) Declared in NSStream.h read:maxLength: Reads up to a given number of bytes into a given buffer. - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len NSInputStream Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 787Parameters buffer A data buffer. The buffer must be large enough to contain the number of bytes specified by len. len The maximum number of bytes to read. Return Value A number indicating the outcome of the operation: ● A positive number indicates the number of bytes read; ● 0 indicates that the end of the buffer was reached; ● A negative number means that the operation failed. Availability Available in iOS 2.0 and later. Declared in NSStream.h NSInputStream Class Reference Instance Methods 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 788Inherits from NSObject Conforms to NSObject (NSObject) Framework /System/Library/Frameworks/Foundation.framework Availability Available in iOS 2.0 and later. Declared in Foundation/NSInvocation.h Companion guide Distributed Objects Programming Topics Overview An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system. An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched. An NSInvocation object can be repeatedly dispatched to different targets; its arguments can be modified between dispatch for varying results; even its selector can be changed to another with the same method signature (argument and return types). This flexibility makes NSInvocation useful for repeating messages with many arguments and variations; rather than retyping a slightly different expression for each message, you modify the NSInvocation object as needed each time before dispatching it to a new target. NSInvocation does not support invocations of methods with either variable numbers of arguments or union arguments. You should use the invocationWithMethodSignature: (page 791) class method to create NSInvocation objects; you should not create these objects using alloc (page 1203) and init (page 1229). 2011-10-14 | © 1997, 2011 Apple Inc. All Rights Reserved. 789 NSInvocation Class ReferenceThis class does not retain the arguments for the contained invocation by default. If those objects might disappear between the time you create your instance of NSInvocation and the time you use it, you should explicitly retain the objects yourself or invoke the retainArguments method to have the invocation object retain them itself. Note NSInvocation conforms to the NSCoding protocol, but only supports coding by an NSPortCoder. NSInvocation does not support archiving. Adopted Protocols NSCoding – encodeWithCoder: (page 1999) – initWithCoder: (page 1999) Tasks Creating NSInvocation Objects + invocationWithMethodSignature: (page 791) Returns an NSInvocation object able to construct messages using a given method signature. Configuring an Invocation Object – setSelector: (page 798) Sets the receiver’s selector. – selector (page 796) Returns the receiver’s selector, or 0 if it hasn’t been set.