我有一个NSString
,在我的生命中,我无法弄清楚如何remove spaces
然后选择它last 30 characters
。
错误如:
3/5/13 3:38:30 PM *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType UTF8String]: unrecognized selector sent to instance 0x160bf20'
或
3/5/13 3:30:51 PM *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType length]: unrecognized selector sent to instance 0x160bf20'
我不明白这些错误。
代码:
NSString* m = (NSString*)CFDictionaryGetValue(diskDesc, kDADiskDescriptionVolumeUUIDKey);
[m stringByReplacingOccurrencesOfString:@" " withString:@""]
NSString *newString = [m substringToIndex:[m length]-30];
另一个更新:
NSString * m = (NSString*)CFDictionaryGetValue(diskDesc, kDADiskDescriptionDeviceModelKey);
NSString * v = (NSString*)CFDictionaryGetValue(diskDesc, kDADiskDescriptionVolumeUUIDKey);
if(m)
{
m = [m stringByReplacingOccurrencesOfString:@" " withString:@""];
}
if(v)
{
if([v length] > 30)
{
NSString *newString = [v substringToIndex:[v length]-30];
}
}
答案 0 :(得分:1)
看起来是错误检查的绝佳机会。像这样:
NSString * m = (NSString*)CFDictionaryGetValue(diskDesc, kDADiskDescriptionDeviceModelKey);
if(m)
{
m = [m stringByReplacingOccurrencesOfString:@" " withString:@""]
if([m length] > 30)
{
NSString *newString = [m substringToIndex:[m length]-30];
} else {
NSLog( @"m isn't even 30 characters");
}
} else {
NSLog( @"I didn't get anything useful from my call to CFDictionaryGetValue");
}
答案 1 :(得分:1)
您应该记下DADisk.h头文件中的文档,该文件指定字典为特定键保存的结果类型:
extern const CFStringRef kDADiskDescriptionVolumeUUIDKey; /* ( CFUUID ) */
extern const CFStringRef kDADiskDescriptionDeviceModelKey; /* ( CFString ) */
所有密钥本身都是NSString
/ CFString
s,但是当您向字典询问该密钥的值时,没有任何内容表明它必须是字符串。右括号中的值显示该键的值的类型。
要获取CFUUID
键所包含的kDADiskDescriptionVolumeUUIDKey
的字符串表示形式,可以使用CFUUIDCreateString():
CFUUIDRef UUID = (CFUUIDRef)[(NSDictionary *)diskDesc
objectForKey:(id)kDADiskDescriptionVolumeUUIDKey];
NSString *UUIDString = [(id)CFUUIDCreateString(NULL, UUID) autorelease];
此外,删除kDADiskDescriptionDeviceModelKey
上的无关空格的代码可能如下:
NSString *deviceModel = [(NSDictionary *)diskDesc
objectForKey:(id)kDADiskDescriptionDeviceModelKey];
NSLog(@"deviceModel == '%@'", deviceModel);
NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet
whitespaceAndNewlineCharacterSet];
deviceModel = [deviceModel stringByTrimmingCharactersInSet:whitespaceCharacterSet];
NSLog(@"deviceModel == '%@'", deviceModel);
该代码为我记录了以下内容:
diskArbitrationFinagler[] deviceModel == 'WDC WD6400AAKS-41H2B0 '
diskArbitrationFinagler[] deviceModel == 'WDC WD6400AAKS-41H2B0'
您的stringByReplacingOccurrencesOfString:
会错误地删除WDC
和WD64....
之间的空格。