Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString isEqualToString not working

class define as following:

@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

The source code:

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");
}

The NSLog output as following:

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

Why '5680295' not equal to '5680295"? I have try the following code:

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

The above code show the "equal", but I still don't know why ?

like image 773
Ted Yu Avatar asked Jul 16 '14 12:07

Ted Yu


1 Answers

As others pointed out, the reason why isEqualToString: returns NO is probably because article.articleId is not a string.

self.bookmark.articleId must be an instance of NSString because it responds to isEqualToString:

Make sure articleId is of the expected type:

NSAssert([article.articleId isKindOfClass:[NSString class]], @"bad type in articleId");
like image 90
Nikolai Ruhe Avatar answered Oct 23 '22 11:10

Nikolai Ruhe