0

我有一个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];
    }
}
4

2 回答 2

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");
}
于 2013-03-06T00:08:38.930 回答
1

您应该注意 DADisk.h 头文件中的文档,该文件指定字典将为特定键保存的结果类型:

extern const CFStringRef kDADiskDescriptionVolumeUUIDKey;      /* ( CFUUID       ) */

extern const CFStringRef kDADiskDescriptionDeviceModelKey;     /* ( CFString     ) */

所有键本身都是NSString/ CFStrings,但是当您向字典询问该键的值时,没有什么说它必须是字符串。右侧括号中的值显示了为该键保存的值的类型。

要获取密钥持有的字符串表示CFUUIDkDADiskDescriptionVolumeUUIDKey可以使用 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....

于 2013-03-06T01:01:07.887 回答