如何检查NSArray
上的最后一个对象中的对象?
我试过了:
if ([currentStore isEqual:[Stores lastObject]])
{
//Code
}
但它不起作用。
有什么想法吗?
谢谢!
答案 0 :(得分:0)
或试试这个
BOOL lastElement = false;
NSUInteger index = [stores indexOfObject:currentStore];
if (index != NSNotFound)
{
lastElement = (index == [stores count] - 1);
}
答案 1 :(得分:0)
比特修改试试这个:
NSUInteger index = [stores indexOfObject:currentStore];
if (index == ([stores count]-1))
{
NSLog(@"Yes its Last");
}
答案 2 :(得分:0)
如果你没有覆盖isEqual方法,NSObject :: isEqual的基类实现只检查两个指针是否指向同一个地址。
这篇优秀的文章http://nshipster.com/equality/解释了objc平等原则
以下示例日志 - 测试商店 - 工作正常
@interface Stores : NSObject
@property (strong, nonatomic) NSString* name;
- (instancetype) initWithName:(NSString*) name;
@end
@implementation Stores
- (instancetype) initWithName:(NSString*) name;
{
_name = name;
return self;
}
- (BOOL)isEqualToStores:(Stores*) Stores
{
if (!Stores)
return NO;
if (![_name isEqualToString:Stores.name] )
return NO;
return YES;
}
- (BOOL)isEqual:(id)object
{
if (self == object)
{
return YES;
}
if (![object isKindOfClass:[Stores class]])
{
return NO;
}
return [self isEqualToStores:(Stores *)object];
}
@end
-(void) testStores
{
Stores* last = [[Stores alloc] initWithName:@"5"];
NSArray* arr = @[
[[Stores alloc] initWithName:@"1"],
[[Stores alloc] initWithName:@"2"],
[[Stores alloc] initWithName:@"3"],
[[Stores alloc] initWithName:@"4"],
[[Stores alloc] initWithName:@"5"]
//last
];
if ([last isEqual:[arr lastObject]])
{
NSLog(@"Testing Stores - works fine");
}
else
{
NSLog(@"Testing Stores - opps!?1?!?");
}
}