【发布时间】:2010-11-05 10:47:21
【问题描述】:
首先,我对 Objective-c 和内存管理、指针等非常陌生。毫无疑问,我的问题在于我遗漏了一个简单的点。
我有一个包含整数属性的类:
// Device.H file
@interface Device : NSObject {
@private int nodeLevel;
}
@property (readwrite, assign, nonatomic) int nodeLevel;
// Device.m file
@implementation Device
@synthesize nodeLevel;
- (id)init {
self.nodeLevel = 0;
return self;
}
我创建了一个包含许多设备对象的 NSMutableArray,并分配了节点 ID:
-(NSMutableArray *)getDevices {
...
NSMutableArray *devices = [[NSMutableArray alloc] initWithCapacity:[rDevices count]];
for (NSDictionary *d in rDevices) {
Device *newDevice = [[Device alloc] init] autorelease];
newDevice.nodeLevel = d.nodeLevel;
[devices addObject: newDevice];
}
return [devices autorelease];
}
我的设备数组存储在主应用程序委托中,在那里我分配了一个属性来保存它:
@property (nonatomic, retain) NSMutableArray *devices;
现在这就是我的问题所在。我在另一个控制器类中使用 tableView 来访问我的应用程序委托,从其数组中拉出一个设备,然后使用 int 设置值,但是发生了“奇怪”的事情:
编辑:滑块的最小值/最大值在代码的另一部分分别设置为 0 和 100。
// In method cellForRowAtIndex
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
Device *d = (Device *)[[appDelegate.devices objectAtIndex:indexPath.row]];
// cell is a custom cell with a UISlider object
cell.sliderLevel.value = [d nodeLevel];
当我为设备的 nodeLevel 赋值时,滑块总是最大化,即使 nodeLevel 只等于 1 或 2。
如果我这样做,滑块位于正确的位置,但在我的 tableView 上下滚动时,我最终会收到“EXC_BAD_ACCESS”信号:
// cell is a custom cell with a UISlider object
cell.sliderLevel.value = [[d nodeLevel] intValue];
我怀疑我必须首先将值分配给内存位置?在第二种情况下它有效,但我认为我的 BAD_ACCESS 是 nodeLevel 变为“已发布”或什么的结果?最后一点,我还有一个与 Device 类关联的 NSString 对象。我访问该字符串并将其分配给我的单元格中的标签,它永远不会给我带来问题。
提前感谢您查看。
【问题讨论】:
-
这一行的nodeLevel属性返回什么类型:“newDevice.nodeLevel = d.nodeLevel;”? Device 中的 nodeLevel 属性是一个 int,因此您需要确保 d.nodeLevel 返回一个 int,而不是 NSNumber 对象。
标签: objective-c ios