NSString isEqualToString不起作用

时间:2014-07-16 12:39:02

标签: ios objective-c

类定义如下:

@interface KNBookmark : NSObject
@property (nonatomic, strong) NSString *bookmarkId ;
@property (nonatomic, strong) NSString *novelName ;
@property (nonatomic, strong) NSString *novelId ;
@property (nonatomic, strong) NSString *novelPic ;
@property (nonatomic, strong) NSString *articleId ;
@property (nonatomic, strong) NSString *articleTitle ;
@property (nonatomic, strong) NSNumber *readRate ;
@end

@interface KNArticle : NSObject

@property (nonatomic, strong) NSString *num ;
@property (nonatomic, strong) NSString *articleId ;
@property (nonatomic, strong) NSString *title ;
@property (nonatomic, strong) NSString *subject ;
@property (nonatomic, strong) NSString *text ;
@end

源代码:

for(int i=0;i<count;i++)
{
    KNArticle* article=[self.novel.articles objectAtIndex:i];

    NSLog(@"bookmark articleId='%@' articleId='%@'",self.bookmark.articleId,article.articleId);

    NSLog(@"bookmark articleId class='%@' articleId class='%@'",[self.bookmark.articleId class],[article.articleId class]);

    if([self.bookmark.articleId isEqualToString:article.articleId])
    {
        NSLog(@"equal");
        self.indexArticles=i;
        break;
    }
    else
        NSLog(@"not equal");
}

NSLog输出如下:

2014-07-16 22:56:14.768 novel[12685:90b] bookmark articleId='5680285' articleId='5680285'
2014-07-16 22:56:14.768 novel[12685:90b] bookmark articleId class='__NSCFString' articleId class='__NSCFNumber'
2014-07-16 22:56:14.769 novel[12685:90b] not equal

为什么&#39; 5680295&#39;不等于&#39; 5680295&#34;? 我尝试了以下代码:

NSString* id1=@"5680295";
NSString* id2=@"5680295";
if([id1 isEqualToString:id2])
{
    NSLog(@"equal");
}

上面的代码显示&#34;等于&#34;,但我仍然不知道为什么?

1 个答案:

答案 0 :(得分:5)

正如其他人所指出的,isEqualToString:返回NO的原因可能是因为article.articleId不是字符串。

self.bookmark.articleId必须是NSString的一个实例,因为它响应isEqualToString:

确保articleId属于预期类型:

NSAssert([article.articleId isKindOfClass:[NSString class]], @"bad type in articleId");