ios - NSInteger 到 NSString 被误解

标签 ios objective-c xcode xcode6

我有一个关于 NSIntegerNSString 的问题 我一直在努力,但没有运气。 但是出于某种奇怪的原因,我的 NSInteger 之一会,但我不知道为什么 我有这个方法:

//Lets say loc_id = 869
-(void)addResource:(NSInteger)loc_id
{
   //[loc.chosenLocations addObject:[NSString stringWithFormat@"%@",loc_id]];
   NSLog([NSString stringWithFormat:@"addResource: loc_id:%@",loc_id]);
}

结果不好

Because its giving me: addResource: loc_id:20987787696 in the debugger of xcode

应该是 loc_id:860

当我尝试使用 loc_id = 8 时 它工作得很好为什么会有这种奇怪的行为 或者我误解了什么感谢您的提示和帮助。 当我以字符串格式使用 %@ 时,它适用于 loc_id = 8 但是当我尝试使用 %d 这是正常使用,它也会导致 loc_id:20987787696 怎么会?

方法的使用:

-(IBAction)switchChanged:(id)sender {
  UISwitch *switchControl = sender;
  [loc addResource:switchControl.tag] 
 }

 -(void)addSwitch:(NSInteger)aid
 {
    UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectMake(x,y,w,h)]];
    sw.tag = aid;
    [sw addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEvenValueChanged]];
    [self.View addSubview:sw];
 }

 //Data is dynamic (NSObject) but for example i will exclude the dynamic data.
 for(int i = 0; i < 20; i++)
 {
   NSInteger *loc_id = 868;
   [self addSwitch:loc_id];

 }

在某个时候我想将它插入到上面注释的 NSMutableArray 中,但我希望它的值为 869,它给了我 2071894069 我想要 int 的值而不是内存的东西

亲切的问候, 斯特凡

最佳答案

您应该使用 %li@ld 而不是 %@,并删除 stringWithFormat: 调用在 NSLog 中(它已经需要一种格式):

NSLog(@"addResource: loc_id:%li",loc_id);

%@ 是格式化对象描述和字符串的选择器。 %li 是将您的整数转换为 long,并防止最终的编译器警告。


编辑:

在评论中提出了很多问题之后,您的代码中还有另一个错误:

NSInteger *loc_id = 868;

您不应将 loc_id 作为指针启动。改用:

NSInteger loc_id = 868;

编辑#2:

正如聊天中所讨论的,问题出在从保存它的数组/字典中提取 NSInteger 值的方式。

关于ios - NSInteger 到 NSString 被误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26179400/

相关文章:

c++ - C++中的抽取

iphone - 如何使开关转移到另一个 View Controller ?

iphone - 如何将多个自定义 View Controller 与导航 Controller 一起使用?

ios - 检查应用程序是否通过 iOS 上的今日小部件启动...?

ios - 保持 UIScrollView 的 subview 不受 ScrollView 内容偏移的影响

iphone - 为什么我的 ASIHTTPRequest 文件显示 ARC 错误?

ios - 重定向到 Twitter 登录的设置屏幕

iphone - ios如何缓存数据

ios - 如何在swift 4中的 subview 中填充背景图像?

ios - 苹果 watch CMDeviceMotion 没有给我很好的读数