Objective c 从NSMutableArray检索自定义对象
我的问题非常类似于,但是我没有从我的Objective c 从NSMutableArray检索自定义对象,objective-c,Objective C,我的问题非常类似于,但是我没有从我的NSMutableArray返回nil,我已经分配并初始化了我的NSMutableArray。如何从索引处的时间线对象中检索名称值,例如,3。 类似于以下内容: NSLog(@"tlresults: %@",(Timeline *)[tlresults objectAtIndex:3].name); 并返回索引3的Timeline.name值 时间轴.h @interface Timeline : NSObject { NSString *_name
NSMutableArray
返回nil
,我已经分配并初始化了我的NSMutableArray
。如何从索引处的时间线
对象中检索名称
值,例如,3。
类似于以下内容:
NSLog(@"tlresults: %@",(Timeline *)[tlresults objectAtIndex:3].name);
并返回索引3的Timeline.name值
时间轴.h
@interface Timeline : NSObject
{
NSString *_name;
NSInteger _up;
NSInteger _down;
NSInteger _timeofdatapoint;
}
@property (nonatomic,retain) NSString *name;
@property (nonatomic) NSInteger up;
@property (nonatomic) NSInteger down;
@property (nonatomic) NSInteger timeofdatapoint;
@end
Timeline.m
#import "Timeline.h"
@implementation Timeline
@synthesize name = _name;
@synthesize up = _up;
@synthesize down = _down;
@synthesize timeofdatapoint = _timeofdatapoint;
@end
将对象添加到和测试检索的函数:
#import "Timeline.h"
...
NSMutableArray *tlresults = [[NSMutableArray alloc] init];
for (int i=0; i<10; i++) {
Timeline *tlobj = [Timeline new];
tlobj.name = username;
tlobj.up = 2*i;
tlobj.down = 5*i;
tlobj.timeofdatapoint = 2300*i;
[tlresults addObject:tlobj];
[tlobj release];
}
NSLog(@"tlresults count: %d",[tlresults count]);
NSLog(@"marray tlresults: %@",(Timeline *)[tlresults objectAtIndex:3]);
...
您需要重写description方法,为将使用NSLog()打印的对象提供您自己的描述。
由于您没有重写此方法,因此使用了NSObject的方法,它只打印对象的内存地址 例如:
- (NSString*) description
{
return [NSString stringWithFormat: @"Name: %@ up: %li down: %li time of data point: %li",_name,_up,_down,_timeofdatapoint);
}
此外,按照惯例,属性名称不应为:
@property (nonatomic) NSInteger timeofdatapoint;
但这是:
@property (nonatomic) NSInteger timeOfDataPoint;
编写强制转换以便访问类实例的声明属性的正确方法是:
NSLog(@"tlresults: %@",((Timeline *)[tlresults objectAtIndex:3]).name);
或
或者,如果您需要访问许多属性:
Timeline *timelineAtIndex3 = [tlresults objectAtIndex:3];
NSLog(@"tlresults: %@", timelineAtIndex3.name);
您期望的输出是什么?与您的代码相比,我看不出您的代码输出有什么令人惊讶的地方。“Timeline:0x7292eb0”是指内存地址为0x7292eb0的Timeline对象。顺便说一句:无需声明实例变量或使用@synthesis。@Occlus虽然我的语法明显错误,但我的目标是实现上面描述的“最终…[和nslog语句]”@bbum您是正确的,先生。我没有意识到这一点。非常感谢。我应该提到,我已经覆盖了-(NSString*)描述;但是我想返回一个可解析的时间线对象,这样我就可以遍历时间线对象数组并返回所有名称(例如:NSLog(@“tlresults:%@),(Timeline*)[tlresults objectAtIndex:3].name);我将编辑这个问题。是的。非常感谢。现在看起来很明显。谢谢你这样一个充实的回答。
NSLog(@"tlresults: %@",[(Timeline *)[tlresults objectAtIndex:3] name]);
Timeline *timelineAtIndex3 = [tlresults objectAtIndex:3];
NSLog(@"tlresults: %@", timelineAtIndex3.name);