Search code examples
objective-cmacoscocoaxmldocument

How can append Data to NSmutableData in Cocoa


I want to add new NSdata = x20 (ASCII) , it's a space at last in NSMutableData to enough fixed byes. Example: NSmuatabledata has 400 bytes, but i need this NSMutableData has 600 bytes. So that i want to add 200 byes (x20 in HEX) at last this nsmutableData. How can i do that? please help me. thanks in advance

// write xmlDoc to file
NSData* xmlData = [xmlDoc XMLDataWithOptions:NSXMLNodePreserveAll];
NSLog(@"xmlData %@",xmlData);
NSMutableData * datawrite = [xmlData mutableCopy ] ;
NSArray *array = [[NSArray alloc] init]; // i dont know how to add x20 (hex) to this array 
[datawrite appendData:[[NSString stringWithFormat:@"%@", array] dataUsingEncoding:NSUTF8StringEncoding]];

Solution

  • NSMutableData *datawrite = ...
    NSUInteger oldLength = [datawrite length];
    NSUInteger newLength = 600;
    if (newLength > oldLength ) {
        // extend mutable data object:
        [datawrite setLength:newLength];
    
        // fill appended bytes with space characters:
        char *bytes = [datawrite mutableBytes];
        memset(bytes + oldLength, ' ', newLength - oldLength);
    }