开发者

Auto Boxing of primitives

开发者 https://www.devze.com 2022-12-23 05:36 出处:网络
I can\'t seem to figure out how to get Objective-c to auto box my primitives. I assumed that i would be able to do the following

I can't seem to figure out how to get Objective-c to auto box my primitives.

I assumed that i would be able to do the following

float foo = 12.5f;
NSNumber* bar;

bar = foo;
开发者_如何学Python

However i find that i have used to the more verbose method of

float foo = 12.5f;
NSNumber* bar;

bar = [NSNumber numberWithFloat:foo];

Am i doing it wrong or is this as good as it gets?


Unfortunately, Objective-C does not do auto-boxing or unboxing of primitive types to NSNumber. When put that way, it may be clear why: Objective-C has no concept of NSNumber, a class in the Cocoa Foundation framework. As a small superset of C, Objective-C doesn't have a "native" numeric object type--just the native C types.

Edit Aug 2012 As of Xcode 4.4 (and LLVM 4.0), you can now use some syntactic sugar to wrap numbers. Following your example, these "boxed expressions" now work:

float foo = 12.5f;
NSNumber* bar;

bar = @(foo);
bar = @12.5f;


Clang 3.1 and Apple LLVM 4.0 (included in Xcode 4.4) support a new boxing feature: http://clang.llvm.org/docs/ObjectiveCLiterals.html#objc_boxed_expressions

You're now able to write:

NSNumber *bar = @(foo);

as well as:

NSNumber *bar = @12.5F;

So it just got a little better. :)


Auto unboxing is possible in Objective c...

Please read the following code

@interface Class1 : NSObject
@property(nonatomic,assign)int intval;
@end 

///Now we are going to instantiate class1 in class2 and we are gonna assign the instance variable a value through reflection

@implementation Class2

-(void)TestClass1
{
  Class1 *clsObj=[[Class1 alloc]init];

  [clsObj setValue:@"3" forKey:@"intval"];

  NSLog(@"%d",clsObj.intval);

}

@end

If u run the above code you will get value 3...There is no error

[clsObj setValue:@"3" forKey:@"intval"];

The intVal is given string value 3 and it's auto unboxed to assign as int type to the instance variable intVal

0

精彩评论

暂无评论...
验证码 换一张
取 消