【问题标题】:Setting a float in NSObject throws doesNotRecognizeSelector error在 NSObject 中设置浮点数会引发 doesNotRecognizeSelector 错误
【发布时间】:2016-11-30 05:27:39
【问题描述】:

我在尝试设置 float 的属性时不断收到错误消息。

我有一个Download 类NSObject,它有一个原始的float。该类正在从NSURLSessionDownloadTask 委托方法调用,因为该类下载了更新进度所需的文件。

虽然我不断收到错误setProgress: unrecognized selector sent to instance

知道为什么吗?

我的下载 NSObject 类.h

@interface Download : NSObject {

}
@property (nonatomic, strong) NSString* url;  
@property (assign) float progress;
- (id) initWithUrl:(NSString*)url;

@end

我的下载 NSObject 类.m

#import "Download.h"

@implementation Download

- (id) initWithUrl:(NSString*)url {
       if (self = [super init]) {
           self.url = url;
       }

    return self;

}
@end

被调用的方法

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
  {
 //OTHER STUFF

 Download * download = [[Download alloc] initWithUrl@"SomeUrl"];
 download.progress = (float)(totalBytesWritten)/(float)totalBytesExpectedToWrite;

}

错误

[__NSCFString setProgress:]: 无法识别的选择器发送到实例 0x7fbec1cbfee0

由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'-[__NSCFString setProgress:]: 无法识别的选择器发送到实例 0x7fbec1cbfee0' 第一次抛出 调用栈:

0 CoreFoundation __exceptionPreprocess + 165

1 libobjc.A.dylib objc_exception_throw + 48

2 CoreFoundation -[NSObject(NSObject) doesNotRecognizeSelector:] + 205

3 CoreFoundation 转发 + 970

4 核心基础_CF_forwarding_prep_0 + 120

5 下载管理器-[MainManagerViewController URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:] + 420

6 CFNetwork __113-[NSURLSession delegate_downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:completionHandler:]_block_invoke + 50

7 基金会_NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK_ + 7

【问题讨论】:

  • 请添加init with url实现代码...
  • @EvgenyKarkan 我更新了问题。
  • 尝试使用NSNumber代替float,如果可行,那么你可以将nsnumber转换为float。 @Firemarble
  • 那里没有typedef NSString Download;,是吗?
  • 我认为它是复制和粘贴/堆栈溢出格式错误。它就在那里。

标签: ios objective-c nsobject primitive-types nsurlsessiondownloadtask


【解决方案1】:

这样的错误通常是由于对象的释放而发生的。在您的代码示例中,Download 对象在您设置进度值后立即被释放。如果您没有对该对象的强引用,则指向它的指针将变为无效,因此可以指向任何其他对象,在您的情况下是一些随机的 NSString。

Download * download = [[Download alloc] initWithUrl@"SomeUrl"];
download.progress = (float)(totalBytesWritten)/(float)totalBytesExpectedToWrite;

// Download object deallocated

【讨论】:

    【解决方案2】:

    查看您的 MainManagerViewController。您将 setProgress 发送到 NSString * 而不是 Download 对象。可能是 MainManagerViewController URLSession 的参数之一:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2011-03-04
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2017-11-12
      • 2013-10-19
      • 2013-07-16
      相关资源
      最近更新 更多