![](/img/trans.png)
[英]Defined behavior of cast from unsigned char * to char * in Objective-C
[英]How to compare unsigned char in Objective-C?
在大量閱讀這里的答案后,我仍然沒有設法讓它發揮作用。 我有一個屬性:
@property (nonatomic,readonly) unsigned char theValue;
在nonMutableClass
類中,並且可以在mutableClass
使用
-(void)setTheValue:(unsigned char)value
使用 API,我可以簡單地做[mutableClass setTheValue:1];
,但是,我如何檢查/比較它? 使用此代碼檢查它似乎不會返回 true,即使它實際上是 true:
if ([nonMutableClass.theValue == 1]) NSLog(@"TRUE");
if ([[NSString stringWithUTF8String:(char *)(nonMutableClass.theValue)] isEqualToString:@"1"]) NSLog(@"TRUE");
//This one returned as compiler error as "cast to 'char *' from smaller integer type 'unsigned char'"
任何的想法? 提前致謝。
嘗試像這樣將字符轉換為字符串。
NSString * s = [NSString stringWithFormat:@"%c", c ];
或者
NSString * s = [NSString initWithBytes:&c length:1 encoding:NSASCIIStringEncoding];
注意我在這里使用 ASCII。 更改為 UTF8 或您的c
代表的任何內容。 第一種選擇使用 C printf 進行轉換。
然后比較,像
[str1 cmp:str2 options:x]
您需要將x
設置為適合您情況的內容。 這里有一些建議...
您或 ( |
) 將這些組合在一起以獲得您需要的東西。 我提到這些是因為手冊沒有給你所有這些,而且在處理角色時它們非常方便。 您正在使用的角色類型將決定您需要哪些角色。
另外,有趣的是,如果您只比較字符串的第一個字符,然后進行比較
[s substringToIndex:1]
作為替代
[s1 compare:s2 options:x range:r]
由於某些有趣的原因而失控。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.