Brief Intro to Value Objects of Foundation Framework

Value Objects

The Foundation Framework value object classes implement object-oriented wrappers for primitive data types, along with general-purpose system information, tools, and locale support. The NSCalendarNSDateNSCalendarDate,NSDateComponents, and NSTimeZone classes provide support for date and time programming and formatting. The NSValueNSNumberNSDecimalNumber, andNSDecimalNumberHandler classes provide object-oriented wrappers for primitive data types, which can then be manipulated and/or added to collection objects. TheNSDataNSMutableData, and NSPurgeableData classes provide object-oriented wrappers for byte buffers. NSValueTransformer is used to transform values from one representation to another. NSNull is a singleton object used to represent null values in collection objects that don’t allow nil values. NSLocale provides support for locales, a collection of information used to adapt software for a specific region or language. NSCache provides an in-memory system cache for the temporary storage of objects that are expensive to re-create.

NSValue

The NSValue class is a container for a single data item. It can hold both C and Objective-C data types (including primitives) of constant length and is typically used to allow an item to be stored in a collection object (NSArrayNSSet, etc.), because these require their elements to be objects. The code fragment in Listing 10-3 creates an NSValue instance from a value of type int.

Listing 10-3.  Creating an NSValue Instance

int ten = 10;
int *tenPtr = &ten;
NSValue *myInt = [NSValue value:&tenPtr withObjCType:@encode(int *)];

Note that the type is specified using an @encode directive. This value can now be stored in a collection object. The following statement retrieves the int value of theNSValue object and assigns this value to the variable result.

int result = *(int *)[myInt pointerValue];

NSNumber

The NSNumber class is a subclass of NSValue that functions as a container for primitive (scalar) types. It defines a set of methods for creating and accessing number objects as primitive types: signed/unsigned charintshort intlong intlong long intNSIntegerfloatdouble, or BOOL types. NSNumberincludes numerous class factory methods (whose names all begin withnumberWith...) for creating and initializing an NSNumber with an input parameter of the specified primitive type. The following statement uses thenumberWithDouble: method to create an NSNumber instance of type double and assign it to a variable named degrees2Radians.

NSNumber *degrees2Radians = [NSNumber numberWithDouble:(3.1415/180.0)];

NSNumber also includes initialization methods (whose names all begin withinitWith...) to initialize an allocated NSNumber object with the input parameter value. The corresponding NSNumber ...Value methods (one for each of the supported types) can be used to retrieve a primitive value from an NSNumberobject, for example:

double d2r = [degrees2Radians doubleValue];

NSNumber also includes a stringValue method to get the string representation of an NSNumber instance.

NSDecimalNumber

NSDecimalNumber is a subclass of NSNumber that is used to perform decimal arithmetic. It includes methods for creating and initializing decimal numbers, and methods for performing standard arithmetic operations (addition, subtraction, multiplication, division, etc.). It is especially useful for performing these operations on numbers where rounding errors can be significant (for example, with currency).Listing 10-4 adds two NSDecimalNumber objects and assigns the result to anNSDecimalNumber object named sum.

Listing 10-4.  Adding Two Numbers Using NSDecimalNumber

NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:@"2.56"];
NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:@"7.78"];
NSDecimalNumber *sum = [num1 decimalNumberByAdding:num2];

The NSDecimalNumber methods that perform arithmetic operations include parameters that can be used to specify how calculation errors and rounding are handled.

NSNumber Literals

Objective-C provides language-level support for creating NSNumber literals. Any character, numeric, or Boolean literal that is prefixed with an @ character evaluates to an NSNumber object initialized to that value. The following statements are equivalent:

NSNumber *num = [NSNumber numberWithInt:17];
NSNumber *num = @17;

NSNumber literals are created from scalar values, not expressions. In addition,NSNumber literals are evaluated at runtimethey are not compile-time constants and thus cannot be used to initialize static variables. In essence, the literal @17 is actually shorthand for the expression [NSNumber numberWithInt:17], an object message that is evaluated at runtime. More information on NSNumber literals is provided in Chapter 16, which explores Objective-C literals in depth.

Date and Time Support

The NSCalendarNSDateNSCalendarDateNSDateComponents, and NSTimeZoneclasses provide support for date and time programming and formatting. An NSDateinstance represents an absolute timestamp. The following statement creates a date that represents the current time.

NSDate *now = [[NSDate alloc] init];

The following statements compare two dates and return an NSComparisonResultthat indicates whether the input date is later, the same, or earlier than the receiver’s dates.

NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *tomorrow = [now dateByAddingTimeInterval:secondsPerDay];
NSComparisonResult *result = [now compare:tomorrow];

The NSCalendar class encapsulates calendar information used to organize periods of time. It provides an implementation for several different calendars, including the Buddhist, Gregorian, Hebrew, Islamic, and Japanese calendars. The following statement returns a calendar for the current user’s chosen locale.

NSCalendar *currentCalendar = [NSCalendar currentCalendar];

The following statement creates a Gregorian calendar.

NSCalendar *gregorianCalendar = [[NSCalendar alloc]
                                initWithCalendarIdentifier:NSGregorianCalendar];

NSCalendar provides methods for retrieving the component elements of a date in a calendar, represented as NSDateComponents objects.

The NSDateComponents class represents the component elements of a date/time. It is used to set/get these elements, and also specify a time interval. The following statements retrieve date components from a current calendar object with monthly calendar units.

NSDate *date = [NSDate date];
NSDateComponents *components = [currentCalendar components:NSMonthCalendarUnit
                                                    fromDate:date];

NSCache

In computer programming, a cache is a mechanism that stores data so that future requests for the same data can be retrieved more quickly. They are commonly used to store objects that are expensive to re-create. The Foundation FrameworkNSCache class provides an in-memory system cache for the temporary storage of objects that are expensive to re-create. In addition to managing cache values, the class includes methods for managing the cache size, managing discarded objects, and managing the cache delegate. A cache delegate conforms to theNSCacheDelegate protocol, and is sent messages when an object is about to be evicted or removed from the cache. An NSCache instance stores key-value pairs, similar to an NSDictionary (to be discussed later in this chapter). It differs in that it provides autoremoval policies, and thus manages memory utilization. The following code fragment creates an NSCache instance, sets the number of objects the cache can hold, and then adds an object to the cache.

NSCache *cache = [[NSCache alloc] init];
[cache setCountLimit:500];
[cache setObject:@"Hello, World!" forKey:@"greeting"];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值