Sunday, June 2, 2013

NSMutableString appendFormat example in Objective C (iOS).


NSMutableString appendFormat

Adds a constructed string to the receiver.

- (void)appendFormat:(NSString *)format ...

Parameters of [NSMutableString appendFormat]
format
A format string. See “Formatting String Objects” for more information. This value must not be nil.
Important: Raises an NSInvalidArgumentException if format is nil.
...
A comma-separated list of arguments to substitute into format.

NSMutableString appendFormat example.
NSString *trimmedAttributeVariable = [attributeVariable
        stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

...

[NSM appendFormat:@"",
                                 trimmedAttributeVariable, ...

Example of [NSMutableString appendFormat].
NSMutableString's appendFormat.

NSMutableString* aString = [NSMutableString stringWithFormat:@"String with one int %d", myInt];    // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:@"... now has another int: %d", myInt];

NSMutableString appendFormat example.
NSMutableString do it as following.

NSMutableString *myString = [NSMutableString stringWithString:@"some text"];
[myString appendFormat:@"some text = %d", 3];

End of NSMutableString appendFormat example article.

NSMutableString stringWithCapacity example in Objective C (iOS).


NSMutableString stringWithCapacity

Returns an empty NSMutableString object with initial storage for a given number of characters.

+ (id)stringWithCapacity:(NSUInteger)capacity

Parameters
capacity
The number of characters the string is expected to initially contain.

Return Value
An empty NSMutableString object with initial storage for capacity characters.

Discussion of [NSMutableString stringWithCapacity]
The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string.

NSMutableString stringWithCapacity example.
NSMutableString *newPath = [NSMutableString stringWithCapacity:42];
OR

NSMutableString *newPath = [[NSMutableString alloc] init];

I see a lot a declarations written on two lines (i.e.)

NSMutableString *newPath;
newPath = [NSMutableString stringWithCapacity:42];

Example of [NSMutableString stringWithCapacity].
-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSMutableString * outputstring = [NSMutableString stringWithCapacity:[wordToShuffle length]];
    NSMutableSet * usedNumberSet = [NSMutableSet setWithCapacity:[wordToShuffle length]];

    for (int i=0; i<[wordToShuffle length]; i++) {
        int randomnum = arc4random()%[wordToShuffle length];

        while ([usedNumberSet containsObject:[NSNumber numberWithInt:randomnum]]==YES) {
            randomnum = arc4random()%[wordToShuffle length];
        }

        [usedNumberSet addObject:[NSNumber numberWithInt:randomnum]];
        [outputstring appendFormat:@"%c",[wordToShuffle characterAtIndex:randomnum]];
    }

    CCLOG(@"outputstring is:%@",outputstring);
    return outputstring;

 }

NSMutableString stringWithCapacity example.
NSMutableString* message = [NSMutableString stringWithCapacity:15];
[message setString:@"This is spinach"];

BOOL boolA = YES, boolB = NO, boolC = YES;

// add "and" if there are any fruits
if(boolA || boolB || boolC)
    [message appendString:@" and"];

if(boolA)
    [message appendString:@" apples,"];
if(boolB)
    [message appendString:@" oranges,"];
if(boolC)
    [message appendString:@" mangoes,"];

// remove last ","
if(boolA || boolB || boolC)
[message deleteCharactersInRange:NSMakeRange([message length] - 1, 1)];

End of NSMutableString stringWithCapacity example article.

NSMutableData resetBytesInRange example in Objective C (iOS).


NSMutableData resetBytesInRange

Replaces with zeroes the contents of the receiver in a given range.

- (void)resetBytesInRange:(NSRange)range

Parameters
range
The range within the contents of the receiver to be replaced by zeros. The range must not exceed the bounds of the receiver.

Discussion of [NSMutableData resetBytesInRange]
If the location of range isn’t within the receiver’s range of bytes, an NSRangeException is raised. The receiver is resized to accommodate the new bytes, if necessary.

NSMutableData resetBytesInRange example.
NSMutableData *imgData = [NSMutableData data]; /* note, we do not specify a capacity--it's pointless for this use case */
[imgData setData: UIImageJPEGRepresentation(img, 1.0)];
[imgData resetBytesInRange: NSMakeRange(0, [imgData length])];
Or:

NSMutableData *imgData = [[UIImageJPEGRepresentation(img, 1.0) mutableCopy] autorelease];
[imgData resetBytesInRange: NSMakeRange(0, [imgData length])];

Example of [NSMutableData resetBytesInRange].
NSMutableData *postData = [[NSMutableData alloc] init];    [postData resetBytesInRange:NSMakeRange(0, [postData length])];
    [postData setLength:0];

NSMutableData *orgData = [[NSMutableData alloc] init];
    [orgData resetBytesInRange:NSMakeRange(0, [orgData length])];
    [orgData setLength:0];

    orgData = (NSMutableData *)[userInfo dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"-------postData------");
    CFShow(orgData);
    [postData appendBytes:[orgData bytes] length:100];
    CFShow(postData);
    return postData;

End of NSMutableData resetBytesInRange example article.

NSMutableData replaceBytesInRange withBytes length example in Objective C (iOS).


NSMutableData replaceBytesInRange withBytes length

Replaces with a given set of bytes a given range within the contents of the receiver.

- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)replacementBytes length:(NSUInteger)replacementLength

Parameters of [NSMutableData replaceBytesInRange withBytes length]
range
The range within the receiver's contents to replace with bytes. The range must not exceed the bounds of the receiver.
replacementBytes
The data to insert into the receiver's contents.
replacementLength
The number of bytes to take from replacementBytes.

Discussion of [NSMutableData replaceBytesInRange withBytes length]
If the length of range is not equal to replacementLength, the receiver is resized to accommodate the new bytes. Any bytes past range in the receiver are shifted to accommodate the new bytes. You can therefore pass NULL for replacementBytes and 0 for replacementLength to delete bytes in the receiver in the range range. You can also replace a range (which might be zero-length) with more bytes than the length of the range, which has the effect of insertion (or “replace some and insert more”).

NSMutableData replaceBytesInRange withBytes length example.
[source setLength:myStart + myLength];
[source replaceBytesInRange:NSMakeRange(0, myStart)
                  withBytes:NULL
                     length:0];

Example of [NSMutableData replaceBytesInRange withBytes length].
I think you want to do something like this:

[soundFileData replaceBytesInRange:NSMakeRange(4, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength-8)}];
[soundFileData replaceBytesInRange:NSMakeRange(42, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength)}];

NSMutableData replaceBytesInRange withBytes length example.
    NSRange range = NSMakeRange(0, 1);
[requestData replaceBytesInRange:range withBytes:NULL length:0];

End of NSMutableData replaceBytesInRange withBytes length example article.

NSMutableData replaceBytesInRange withBytes example in Objective C (iOS).


NSMutableData replaceBytesInRange withBytes

Replaces with a given set of bytes a given range within the contents of the receiver.

- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes

Parameters
range
The range within the receiver's contents to replace with bytes. The range must not exceed the bounds of the receiver.
bytes
The data to insert into the receiver's contents.

Discussion of [NSMutableData replaceBytesInRange withBytes]
If the location of range isn’t within the receiver’s range of bytes, an NSRangeException is raised. The receiver is resized to accommodate the new bytes, if necessary.

A sample using this method is given in Working With Mutable Binary Data.

NSMutableData replaceBytesInRange withBytes example.
[source setLength:myStart + myLength];
[source replaceBytesInRange:NSMakeRange(0, myStart)
                  withBytes:NULL
                     length:0];

Example of [NSMutableData replaceBytesInRange withBytes].
I think you want to do something like this:

[soundFileData replaceBytesInRange:NSMakeRange(4, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength-8)}];
[soundFileData replaceBytesInRange:NSMakeRange(42, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength)}];

NSMutableData replaceBytesInRange withBytes example.
    NSRange range = NSMakeRange(0, 1);
[requestData replaceBytesInRange:range withBytes:NULL length:0];

End of NSMutableData replaceBytesInRange withBytes example article.

NSMutableData replaceBytesInRange example in Objective C (iOS).


NSMutableData replaceBytesInRange

Replaces with a given set of bytes a given range within the contents of the receiver.

- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes

Parameters
range
The range within the receiver's contents to replace with bytes. The range must not exceed the bounds of the receiver.
bytes
The data to insert into the receiver's contents.

Discussion of [NSMutableData replaceBytesInRange]
If the location of range isn’t within the receiver’s range of bytes, an NSRangeException is raised. The receiver is resized to accommodate the new bytes, if necessary.

A sample using this method is given in Working With Mutable Binary Data.

NSMutableData replaceBytesInRange example.
[source setLength:myStart + myLength];
[source replaceBytesInRange:NSMakeRange(0, myStart)
                  withBytes:NULL
                     length:0];

Example of [NSMutableData replaceBytesInRange].
I think you want to do something like this:

[soundFileData replaceBytesInRange:NSMakeRange(4, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength-8)}];
[soundFileData replaceBytesInRange:NSMakeRange(42, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength)}];

NSMutableData replaceBytesInRange example.
    NSRange range = NSMakeRange(0, 1);
[requestData replaceBytesInRange:range withBytes:NULL length:0];

End of NSMutableData replaceBytesInRange example article.

NSMutableData mutableBytes example in Objective C (iOS).


NSMutableData mutableBytes

Returns a pointer to the receiver’s data.

- (void *)mutableBytes

Return Value
A pointer to the receiver’s data.

Discussion of [NSMutableData mutableBytes]
If the length of the receiver’s data is not zero, this function is guaranteed to return a pointer to the object's internal bytes. If the length of receiver’s data is zero, this function may or may not return NULL dependent upon many factors related to how the object was created (moreover, in this case the method result might change between different releases).

A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData mutableBytes example.
NSMutableData* mydata = [[NSMutableData alloc] init];
[mydata appendData: [@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%p", [mydata mutableBytes]);
NSLog(@"%p", [mydata bytes]);

Example of [NSMutableData mutableBytes].
typedef struct {
    UInt32      riffChunkID; // Always RIFF, in big endian. Integer fields are little-ending.
    UInt32      fileLength;
    UInt32      waveFileID; // 'WAVE' for Wave files.
    UInt32      formatChunkID; // 'fmt '
    UInt32      formatChunkSize;
    SInt16      formatTag; // Wave Format ID: see constants
    SInt16      channels; // Number of Channels: 1=mono, 2=stereo
    SInt32      sampleRate; // Sample Rate: samples per second
    SInt32      bytesPerSec; // sampleRate * blockAlign
    SInt16      blockAlign; // sample frame size = channels * sampleSize / 8
    SInt16      bitsPerSample; // sampleSize (8 or 16), also two's-complement for 16-bit, offset for 8-bit
    UInt32      dataChunkID;  // 'data'
    UInt32      dataChunkSize;
} WaveHeader;

int tfChannels = 1; // mono
int tfSampleRate = 44100;
int tfBitsPerSample = 16;

WaveHeader *header = [maindata mutableBytes];

header->riffChunkID = CFSwapInt32HostToBig ('RIFF');
header->fileLength = CFSwapInt32HostToLittle ([maindata length] - 8);
header->waveFileID = CFSwapInt32HostToBig ('WAVE');

header->formatChunkID = CFSwapInt32HostToBig ('fmt ');
header->formatChunkSize = CFSwapInt32HostToLittle (16);
header->formatTag = CFSwapInt16HostToLittle (1);
header->channels = CFSwapInt16HostToLittle (tfChannels);
header->sampleRate = CFSwapInt32HostToLittle (tfSampleRate);
header->bytesPerSec = CFSwapInt32HostToLittle (tfSampleRate * tfBitsPerSample / 8 * tfChannels);
header->blockAlign = CFSwapInt16HostToLittle (tfBitsPerSample / 8 * tfChannels);
header->bitsPerSample = CFSwapInt16HostToLittle (tfBitsPerSample);
header->dataChunkID = CFSwapInt32HostToBig ('data');
header->dataChunkSize = CFSwapInt32HostToLittle ([maindata length] - 44);

NSMutableData mutableBytes example.
NSMutableData* mutableData = [NSMutableData dataWithLength: someLength];
void* bitmapData = [mutableData mutableBytes];
CGContextRef context = CGBitmapContextCreate(bitmapData,...);
// ...use context
CGContextRelease(context);

End of NSMutableData mutableBytes example article.