在引用类中,IOS NSString属性始终为空

3
这是我的@interface定义;
@interface Thumbnail : UIView <NSCoding>{
    NSMutableString *imageCacheKeyBase;
}
@property (nonatomic, copy) NSMutableString  *imageCacheKeyBase;
@end

这是我的实现代码:

@synthesize imageCacheKeyBase;

然后在Thumbnail类中的initWithAsset方法中:

self.urlString = [[_asset.defaultRepresentation.url absoluteString] copy];
c  = (char*)[urlString UTF8String];

while (*c != '=') 
    ++c;
++c;

self.imageCacheKeyBase = [NSString stringWithFormat:@"%s_", c];

而当缩略图分配类尝试引用thumbnail.imageCacheKeyBase时,该可恶的东西是空的。我已经尝试了无数种方法来使字符串变量成为缩略图的属性。我甚至尝试过简单地使用self.imageCacheKeyBase = @“dave”。可什么也没有发生。我尝试了保留和保留保留(我知道这很愚蠢,但我尝试了任何可能的方法)。我甚至尝试了将属性设为char *。
我一整天都在研究这个问题。
请帮帮我。
2个回答

1

在某个地方,有些东西是空的。尝试使用NSLog记录每个对象或数据类型的值。

NSLog(@"My first string is %@, the char is %s, the final string is %@", [_asset.defaultRepresentation.url absoluteString], c, self.imageCacheKeyBase);

嗯,据我所知,C字符串就是char *。自从Kernigan和Richie设计出C语言以来,%s和char *就像花生酱和果冻一样紧密相连。不过,我想我的帖子可能有点误导人。实际上,C被声明为char *c;你提到你看到了其他问题。比如什么? - user953175

0

看起来你正在尝试获取输入URL中包括等号=在内的所有内容。我建议你不要转换为UTF-8字符串(除非你有没有提到的充分理由),而是做如下处理:

self.urlString = [[_asset.defaultRepresentation.url absoluteString] copy];

NSRange range = [self.urlString rangeOfString@"="];
if (range.location != NSNotFound)
{
    self.imageCacheKeyBase = [NSString stringWithFormat:@"%s=", [self.urlString subStringToIndex:range.location];
}

我也会在.h文件中这样声明imageCacheKeyBase

@property (nonatomic, retain) NSString *imageCacheKeyBase;

除非你需要它是可变的,否则不需要。如果你需要它是可变的,在我的代码片段中,将[NSString stringWithFormat...更改为[NSMutableString stringWithFormat...。由于你在这个类中创建了字符串,所以只需要保留,这比复制更好。

此外,你在代码片段中引用了self.urlString,但它没有在@interface中声明。也许你只是想让它成为一个临时的局部变量,当你生成imageCacheKeyBase时?如果是这样,请将我上面代码片段的第一行更改为:

NSString* urlString = [_asset.defaultRepresentation.url absoluteString];

absoluteString 返回一个自动释放的字符串,因此不需要释放它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接