因为我们知道,我们可以添加使用类别和运行方法,如在Objective-C的变量
objc_setAssociatedObject和objc_getAssociatedObject.例如:
#import <objc/runtime.h>
@interface Person (EmailAddress)
@property (nonatomic, readwrite, copy) NSString *emailAddress;
@end
@implementation Person (EmailAddress)
static char emailAddressKey;
- (NSString *)emailAddress {
return objc_getAssociatedObject(self,
&emailAddressKey);
}
- (void)setEmailAddress:(NSString *)emailAddress {
objc_setAssociatedObject(self,
&emailAddressKey,
emailAddress,
OBJC_ASSOCIATION_COPY);
}
@end
Run Code Online (Sandbox Code Playgroud)
但有人知道做什么objc_getAssociatedObject或objc_setAssociatedObject做什么?我的意思是,我们添加到对象(这里self)的变量存储在哪里?和变量之间的关系self?
我需要从Internet下载大文件,并将其保存到本地磁盘.
首先,我保存这样的数据:
- (void)saveToLocalFile:(NSData *)data withOffset:(unsigned long long)offset{
NSString* localFile = [self tempLocalFile];
dispatch_async(mFileOperationQueue_, ^{
NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath:localFile];
if (fileHandle == nil) {
[data writeToFile:localFile atomically:YES];
return;
}
else {
[fileHandle seekToFileOffset:offset];
[fileHandle writeData:data];
[fileHandle closeFile];
}
});
}
Run Code Online (Sandbox Code Playgroud)
由于AFNetworking使用NSOutputstream将数据保存到本地是这样的:
NSUInteger length = [data length];
while (YES) {
NSInteger totalNumberOfBytesWritten = 0;
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < (NSInteger)length) {
numberOfBytesWritten = …Run Code Online (Sandbox Code Playgroud)