Returns an initialized NSMutableData object capable of holding the specified number of bytes.
- (id)initWithCapacity:(NSUInteger)capacity
Parameters
capacity
The number of bytes the data object can initially contain.
Return Value
An initialized NSMutableData object capable of holding capacity bytes.
Discussion of [NSMutableData initWithCapacity]
This method doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed, so aNumItems simply establishes the object’s initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. This method sets the length of the data object to 0.
If the capacity specified in aNumItems is greater than four memory pages in size, this method may round the amount of requested memory up to the nearest full page.
NSMutableData initWithCapacity example.
self.receiveData = [[[NSMutableData alloc] initWithCapacity:0] autorelease];
OR
Creates and returns an NSMutableData object capable of holding the specified number of bytes.
+ (id)dataWithCapacity:(NSUInteger)aNumItems
Parameters
aNumItems
The number of bytes the new data object can initially contain.
Return Value
A new NSMutableData object capable of holding aNumItems bytes.
Discussion of [NSMutableData dataWithCapacity]
This method doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed, so aNumItems simply establishes the object’s initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. This method sets the length of the data object to 0.
If the capacity specified in aNumItems is greater than four memory pages in size, this method may round the amount of requested memory up to the nearest full page.
NSMutableData dataWithCapacity example.
#include
-(NSData*)create20mbRandomNSData
{
int twentyMb = 20971520;
NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb];
for( unsigned int i = 0 ; i < twentyMb/4 ; ++i )
{
u_int32_t randomBits = arc4random();
[theData appendBytes:(void*)&randomBits length:4];
}
return theData;
}
Example of [NSMutableData dataWithCapacity].
- (NSData *)randomDataWithBytes: (NSUInteger)length {
NSMutableData *mutableData = [NSMutableData dataWithCapacity: length];
for (unsigned int i = 0; i < size; i++) {
NSInteger randomBits = arc4random();
[mutableData appendBytes: (void *) &randomBits length: 1];
} return mutableData;
}
NSMutableData dataWithCapacity example.
encoding:
NSMutableData * data = [NSMutableData dataWithCapacity:0];
float z = ...;
[data appendBytes:&z length:sizeof(float)];
decoding:
NSData * data = ...; // loaded from bluetooth
float z;
[data getBytes:&z length:sizeof(float)];
NSDataWritingOptions
Options for methods used to write NSData objects.
enum {
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
};
typedef NSUInteger NSDataWritingOptions;
Constants
NSDataWritingAtomic
A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.
NSDataWritingWithoutOverwriting
Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.
NSDataWritingFileProtectionNone
A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.
Available in iOS 4.0 and later.
Declared in NSData.h.
NSDataWritingFileProtectionComplete
A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.
NSDataWritingFileProtectionCompleteUnlessOpen
A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.
NSDataWritingFileProtectionMask
A mask to use when determining the file protection options assigned to the data.
NSData * data = // Your decrypted file data.
NSString * fileName = // Whatever you want to name your file.
NSString * path = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
NSURL * url = [NSURL URLWithString:path];
NSError * error = nil;
BOOL success = [data writeToURL:url
options:NSDataWritingFileProtectionComplete
error:&error];
if (success) {
// Give the URL to Quick Look.
}
else {
// An error happened. See the 'error' object for the details.
}
Example of [NSData NSDataWritingFileProtectionComplete].
NSDataWritingOptions
Options for methods used to write NSData objects.
enum {
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
};
typedef NSUInteger NSDataWritingOptions;
Constants
NSDataWritingAtomic
A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.
NSDataWritingWithoutOverwriting
Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.
NSDataWritingFileProtectionNone
A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.
Available in iOS 4.0 and later.
Declared in NSData.h.
NSDataWritingFileProtectionComplete
A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.
NSDataWritingFileProtectionCompleteUnlessOpen
A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.
NSDataWritingFileProtectionMask
A mask to use when determining the file protection options assigned to the data.
// Check if the directory already exists
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSDataWritingOptions
Options for methods used to write NSData objects.
enum {
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
};
typedef NSUInteger NSDataWritingOptions;
Constants
NSDataWritingAtomic
A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.
NSDataWritingWithoutOverwriting
Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.
NSDataWritingFileProtectionNone
A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.
Available in iOS 4.0 and later.
Declared in NSData.h.
NSDataWritingFileProtectionComplete
A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.
NSDataWritingFileProtectionCompleteUnlessOpen
A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.
NSDataWritingFileProtectionMask
A mask to use when determining the file protection options assigned to the data.
Parameters of [NSData writeToFile options error]
path
The location to which to write the receiver's bytes.
mask
A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.
errorPtr
If there is an error writing out the data, upon return contains an NSError object that describes the problem.
Return Value of [NSData writeToFile options error]
YES if the operation succeeds, otherwise NO.
Parameters of [NSData writeToFile]
path
The location to which to write the receiver's bytes.
mask
A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.
errorPtr
If there is an error writing out the data, upon return contains an NSError object that describes the problem.
Return Value of [NSData writeToFile]
YES if the operation succeeds, otherwise NO.
NSDataReadingOptions
Options for methods used to read NSData objects.
enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
};
typedef NSUInteger NSDataReadingOptions;
Constants
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
NSDataReadingUncached
A hint indicating the file should not be stored in the file-system caches.
For data being read once and discarded, this option can improve performance.
NSDataReadingMappedAlways
Hint to map the file in if possible.
This takes precedence over NSDataReadingMappedIfSafe if both are given.
NSError *error = nil;
NSURL *url = [NSURL URLWithString:[imageLinks objectAtIndex:0]];
NSData *tdata = [NSData dataWithContentsOfURL:url options: NSDataReadingMappedAlways error:&error];
if (error) {
NSLog(@"%@", [error localizedDescription]);
}else {
// no error, this one is being called within my app
NSLog(@"Data loaded successfully");
}
NSDataReadingOptions
Options for methods used to read NSData objects.
enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
};
typedef NSUInteger NSDataReadingOptions;
Constants
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
NSDataReadingUncached
A hint indicating the file should not be stored in the file-system caches.
For data being read once and discarded, this option can improve performance.
NSDataReadingMappedAlways
Hint to map the file in if possible.
This takes precedence over NSDataReadingMappedIfSafe if both are given.
NSData NSDataReadingUncached example.
NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:yourURL options:NSDataReadingUncached error:&error];
if (error) {
NSLog(@"%@", [error localizedDescription]);
[error release];
} else {
NSLog(@"Data has loaded successfully.");
}
Example of [NSData NSDataReadingUncached].
NSError *error = nil;
NSURL *url = [NSURL URLWithString:[imageLinks objectAtIndex:0]];
NSData *tdata = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (error) {
NSLog(@"%@", [error localizedDescription]);
}else {
// no error, this one is being called within my app
NSLog(@"Data loaded successfully");
}
NSDataReadingOptions
Options for methods used to read NSData objects.
enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
};
typedef NSUInteger NSDataReadingOptions;
Constants
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
NSDataReadingUncached
A hint indicating the file should not be stored in the file-system caches.
For data being read once and discarded, this option can improve performance.
NSDataReadingMappedAlways
Hint to map the file in if possible.
This takes precedence over NSDataReadingMappedIfSafe if both are given.
NSData NSDataReadingMappedIfSafe example.
// map the file, rather than loading it
NSData *data = [NSData dataWithContentsOfFile:...whatever...
options:NSDataReadingMappedIfSafe
error:&youdDoSomethingSafeHere];
// we'll maintain a read pointer to our current location in the data
NSUinteger readPointer = 0;
// continue while data remains
while(readPointer < [data length])
{
// work out how many bytes are remaining
NSUInteger distanceToEndOfData = [data length] - readPointer;
// grab at most 16kb of them, being careful not to read too many
NSString *newPortion =
[[NSString alloc] initWithBytes:(uint8_t *)[data bytes] + readPointer
length:distanceToEndOfData > 16384 ? 16384 : distanceToEndOfData
encoding:NSUTF8StringEncoding];
// do whatever we want with the string
[self doSomethingWithFragment:newPortion];
// advance our read pointer by the number of bytes actually read, and
// clean up
readPointer += [newPortion lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
[newPortion release];
}
NSError *error;
NSData *fileData = [NSData dataWithContentsOfFile:tempFile options:NSDataReadingMappedIfSafe error:&error];
if (!fileData) {
NSLog(@"Error %@ %@", error, [error description]);
NSLog(@"%@", tempFile);
//do what you need with the error
}
Returns a data object containing the receiver’s bytes that fall within the limits specified by a given range.
- (NSData *)subdataWithRange:(NSRange)range
Parameters
range
The range in the receiver from which to get the data. The range must not exceed the bounds of the receiver.
Return Value of [NSData subdataWithRange]
A data object containing the receiver’s bytes that fall within the limits specified by range. If range isn’t within the receiver’s range of bytes, raises NSRangeException.
Discussion of [NSData subdataWithRange]
A sample using this method can be found in “Working With Binary Data”.
Parameters of [NSData rangeOfData options range]
dataToFind
The data for which to search. This value must not be nil.
Important: Raises an NSInvalidArgumentException if dataToFind is nil.
mask
A mask specifying search options. The “NSDataSearchOptions” options may be specified singly or by combining them with the C bitwise OR operator.
searchRange
The range within the receiver in which to search for dataToFind. If this range is not within the receiver’s range of bytes, an NSRangeException raised.
Return Value of [NSData rangeOfData options range]
An NSRange structure giving the location and length of dataToFind within searchRange, modulo the options in mask. The range returned is relative to the start of the searched data, not the passed-in search range. Returns {NSNotFound, 0} if dataToFind is not found or is empty (@"").
NSData rangeOfData options range example.
//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F };
NSData *data1 = [[NSData alloc] initWithBytes:ch1
length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00}
length:3];
NSRange range = [data1 rangeOfData:data2
options:0
range:NSMakeRange(0, [data1 length])];
Parameters of [NSData rangeOfData]
dataToFind
The data for which to search. This value must not be nil.
Important: Raises an NSInvalidArgumentException if dataToFind is nil.
mask
A mask specifying search options. The “NSDataSearchOptions” options may be specified singly or by combining them with the C bitwise OR operator.
searchRange
The range within the receiver in which to search for dataToFind. If this range is not within the receiver’s range of bytes, an NSRangeException raised.
Return Value of [NSData rangeOfData]
An NSRange structure giving the location and length of dataToFind within searchRange, modulo the options in mask. The range returned is relative to the start of the searched data, not the passed-in search range. Returns {NSNotFound, 0} if dataToFind is not found or is empty (@"").
NSData rangeOfData example.
//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F };
NSData *data1 = [[NSData alloc] initWithBytes:ch1
length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00}
length:3];
NSRange range = [data1 rangeOfData:data2
options:0
range:NSMakeRange(0, [data1 length])];
Parameters
otherData
The data object with which to compare the receiver.
Return Value
YES if the contents of otherData are equal to the contents of the receiver, otherwise NO.
Discussion of [NSData isEqualToData]
Two data objects are equal if they hold the same number of bytes, and if the bytes at the same position in the objects are the same.
if (![filename isEqualToString:@""]) //this makes sure we did not submitted upload form without selecting file
{
UInt16 separatorBytes = 0x0A0D;
NSMutableData* separatorData = [NSMutableData dataWithBytes:&separatorBytes length:2];
[separatorData appendData:[multipartData objectAtIndex:0]];
int l = [separatorData length];
int count = 2; //number of times the separator shows up at the end of file data
for (unsigned long long i = [dataToTrim offsetInFile] - l; i > 0; i--)
{
[dataToTrim seekToFileOffset:i];
if ([[dataToTrim readDataOfLength:l] isEqualToData:separatorData])
{
[dataToTrim truncateFileAtOffset:i];
i -= l;
if (--count == 0) break;
}
}
Returns a data object initialized with the contents of another data object.
- (id)initWithData:(NSData *)data
Parameters
data
A data object.
Return Value of [NSData initWithData]
A data object initialized with the contents data. The returned object might be different than the original receiver.
Parameters of [NSData initWithContentsOfFile options error]
path
The absolute path of the file from which to read data.
mask
A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.
errorPtr
If an error occurs, upon return contains an NSError object that describes the problem.
Return Value of [NSData initWithContentsOfFile options error]
A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.
NSMutableString* hashStr = [NSMutableString string];
int i = 0;
for (i = 0; i < CC_SHA512_DIGEST_LENGTH; ++i)
[hashStr appendFormat:@"%02x", outputData[i]];
Returns a data object initialized by reading into it the data from the file specified by a given path.
- (id)initWithContentsOfFile:(NSString *)path
Parameters
path
The absolute path of the file from which to read data.
Return Value
A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.
Discussion of [NSData initWithContentsOfFile]
This method is equivalent to initWithContentsOfFile:options:error: with no options.
NSData initWithContentsOfFile example.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableString* hashStr = [NSMutableString string];
int i = 0;
for (i = 0; i < CC_SHA512_DIGEST_LENGTH; ++i)
[hashStr appendFormat:@"%02x", outputData[i]];
Parameters of [NSData initWithBytesNoCopy length freeWhenDone]
bytes
A buffer containing data for the new object. If flag is YES, bytes must point to a memory block allocated with malloc.
length
The number of bytes to hold from bytes. This value must not exceed the length of bytes.
flag
If YES, the returned object takes ownership of the bytes pointer and frees it on deallocation.