【问题标题】:Understanding syntax's (converting NSInteger to NSNumber)理解语法(将 NSInteger 转换为 NSNumber)
【发布时间】:2023-04-04 13:23:01
【问题描述】:

我对正在学习的教程有点困惑。有一行代码如下所示:

location.photoId  = @([Location nextPhotoId]);

我不明白@() 语法的含义,它是什么?该语句中使用的变量有定义:

@interface Location : NSManagedObject <MKAnnotation>
 Location *location = nil;

@property (nonatomic, retain) NSNumber *photoId;

在 Location 类中声明。

+(NSInteger)nextPhotoId{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSInteger photoId = [defaults integerForKey:@"PhotoId"];
                         [defaults setInteger:photoId+1 forKey:@"PhotoId"];
                         [defaults synchronize];
                         return photoId;
}

Location 类中的类方法。

也许没有必要在此处粘贴该代码,但我认为我应该更清楚地说明。我只想知道@([Location nextPhotoId])在这种情况下是什么意思,@()代表什么?

任何帮助将不胜感激!

【问题讨论】:

  • @() 是创建对象字面量的通用语法。 @(some_integer)@(some_floating_point) 创建 NSNumber 对象,@(some_char_pointer) 创建 NSStrings 和 @[]@{} 分别创建 NSArrayNSDictionary 文字。
  • @([Location nextPhotoId]) 仅相当于 [NSNumber numberWithInt:[Location nextPhotoId]];

标签: objective-c core-data


【解决方案1】:

@([Location nextPhotoId]) 只相当于[NSNumber numberWithInt:[Location nextPhotoId]]

@() 是用于定义文字的语法。

方法[Location nextPhotoId] 返回一个整数,并将此整数设置为NSNumber (location.photoId) 使用此语法。

参考:http://cocoaheads.tumblr.com/post/17757846453/objective-c-literals-for-nsdictionary-nsarray-and

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2011-09-21
    • 2012-03-13
    相关资源
    最近更新 更多