简体   繁体   English

NSData的文件路径

[英]file path from NSData

I have NSData that I'm loading from a filePath. 我有要从filePath加载的NSData。 The data is then getting passed around and I need the filePath for where the data came from. 然后数据被传递,我需要数据来自的filePath。

What's the easiest way to do this short of passing the filePath around as an extra parameter? 除了将filePath作为额外参数传递之外,最简单的方法是什么?

Wrap both in a container object that represents the file, eg 将两者都包装在代表文件的容器对象中,例如

@interface File : NSObject

@property (strong) NSData *fileContents;
@property (copy) NSString *filePath;

// perhaps, even a nice constructor to fill these properties
- (id)initWithFilePath:(NSString *)filePath;

@end

While you should probably create a separate struct or class that contains the data you need, you can also add an association to NSData. 虽然您可能应该创建一个单独的包含所需数据的结构或类,但也可以向NSData添加关联。

You can even do it as a category on NSData for convenience... assuming you are using a string... use NSURL if using a URL... that way, none of your other code needs to change... you can still use your NSData as before, with the newly added property. 为了方便起见,您甚至可以在NSData上将其作为类别...假设您使用的是字符串...如果使用URL则使用NSURL ...这样,您的其他代码都不需要更改...您仍然可以通过新添加的属性,像以前一样使用您的NSData。

NOTE: There are lots of reasons to use or not use categories. 注意:使用或不使用类别有很多原因。 I assume you will make the choice best for your code situation, and defer the wars over good/bad use of categories to others. 我认为您将针对您的代码情况做出最佳选择,并将类别使用得当/不好的争论推迟到其他人。

Try something like this... 试试这样的东西...

NSData+AssociatedFilePath.h NSData + AssociatedFilePath.h

#import <Foundation/Foundation.h>

@interface NSData (AssociatedFilePath)
@property (nonatomic, strong) NSString *filePath;
@end

NSData+AssociatedFilePath.m NSData + AssociatedFilePath.m

#import <objc/runtime.h>

static char kFilePath;

@implementation NSData (AssociatedFilePath)

- (void)setFilePath:(NSString*)filePath
{
    objc_setAssociatedObject(self, &kFilePath, filePath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString*)filePath
{
  return objc_getAssociatedObject(self, &kFilePath);
}

@end

Now, in your code, you can do this... 现在,在您的代码中,您可以执行此操作...

NSData *data = // whatever you do to create the data object..
data.filePath = someFilePath;

Whenever you want the file path of a NSData object... 每当您想要NSData对象的文件路径时...

NSString *filePath = myNSDataObject.filePath;

Since it is a category, you can use this on any NSData object, and if a file path was never set, it will just return nil. 由于它是一个类别,因此可以在任何NSData对象上使用它,并且如果从未设置文件路径,则它将仅返回nil。

This is a general solution for any time you need to add behavior to an existing class (of course, following appropriate practices for when to best use categories). 这是在需要将行为添加到现有类中的任何时间的通用解决方案(当然,请遵循适当的做法以最佳使用类别)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM