Saturday, May 11, 2013

NSInputStream inputStreamWithData example ios


inputStreamWithData:

Creates and returns an initialized NSInputStream object for reading from a given NSData object.
+ (id)inputStreamWithData:(NSData *)data
Parameters
data
The data object from which to read. The contents of data are copied.
Return Value( NSInputStream inputStreamWithData example )
An initialized NSInputStream object for reading from data. If data is not an NSData object, this method returns nil.
( NSInputStream inputStreamWithData example )
NSInputStream *dataStream = [NSInputStream inputStreamWithData:[soapBody dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBodyStream:dataStream];
( NSInputStream inputStreamWithData example )
ALAssetRepresentation *rep = [currentAsset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];

iStream = [NSInputStream inputStreamWithData:data];
[iStream open];
( NSInputStream inputStreamWithData example )
NSInputStream *inputStream = [NSInputStream inputStreamwithData:myData]; //assuming myData is NSData*

float myFloat;

if([inputStream hasBytesAvailable]) { // NO if you've already read to the end of myData
  NSInteger bytesRead = [inputStream read:&myFloat maxLength:sizeof(myFloat)];
  NSAssert(bytesRead == sizeof(myFloat);
}

NSInvocationOperation initWithTarget selector object example ios


initWithTarget: selector: object:

Returns an NSInvocationOperation object initialized with the specified target and selector.
- (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg
Parameters
target
The object defining the specified selector.
sel
The selector to invoke when running the operation. The selector may take 0 or 1 parameters; if it accepts a parameter, the type of that parameter must be id. The return type of the method may be void, a scalar value, or an object that can be returned as an id type.
arg
The parameter object to pass to the selector. If the selector does not take an argument, specify nil.
Return Value( NSInvocationOperation initWithTarget selector object example )
An initialized NSInvocationOperation object or nil if the target object does not implement the specified selector.
Discussion( NSInvocationOperation initWithTarget selector object example )
If you specify a selector with a non-void return type, you can get the return value by calling the resultmethod after the operation finishes executing. The receiver tells the invocation object to retain its arguments.
( NSInvocationOperation initWithTarget selector object example )
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
               selector:@selector(loadImagesWithOperation:)
                 object:params];

( NSInvocationOperation initWithTarget selector object example )
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
NSDictionary *argumentDictionary = [NSDictionary dictionaryWithObjectsAndKeys:object1, @"Object1Key", object2, @"Object2Key", nil];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(methodCall:) object:argumentDictionary];
[queue addOperation:operation];
[operation release];

( NSInvocationOperation initWithTarget selector object example )
- (void)myMethod:(NSDictionary*)parameters 
{
    int a = [[parameters objectForKey:@"A"] intValue];
    int b = [[parameters objectForKey:@"B"] intValue];

    // do something with a and b
}


[[NSInvocationOperation alloc] 
    initWithTarget:self
          selector:@selector(myMethod:)
            object:[NSDictionary dictionaryWithObjectsAndKeys:
                     [NSNumber numberWithInt:123], @"A",
                     [NSNumber numberWithInt:456], @"B",
                     nil]];

NSInvocationOperation initWithTarget example ios


initWithTarget :selector:object:

Returns an NSInvocationOperation object initialized with the specified target and selector.
- (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg
Parameters
target
The object defining the specified selector.
sel
The selector to invoke when running the operation. The selector may take 0 or 1 parameters; if it accepts a parameter, the type of that parameter must be id. The return type of the method may be void, a scalar value, or an object that can be returned as an id type.
arg
The parameter object to pass to the selector. If the selector does not take an argument, specify nil.
Return Value( NSInvocationOperation initWithTarget example )
An initialized NSInvocationOperation object or nil if the target object does not implement the specified selector.
Discussion( NSInvocationOperation initWithTarget example )
If you specify a selector with a non-void return type, you can get the return value by calling the resultmethod after the operation finishes executing. The receiver tells the invocation object to retain its arguments.
( NSInvocationOperation initWithTarget example )
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
               selector:@selector(loadImagesWithOperation:)
                 object:params];

( NSInvocationOperation initWithTarget example )
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
NSDictionary *argumentDictionary = [NSDictionary dictionaryWithObjectsAndKeys:object1, @"Object1Key", object2, @"Object2Key", nil];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(methodCall:) object:argumentDictionary];
[queue addOperation:operation];
[operation release];

( NSInvocationOperation initWithTarget example )
- (void)myMethod:(NSDictionary*)parameters 
{
    int a = [[parameters objectForKey:@"A"] intValue];
    int b = [[parameters objectForKey:@"B"] intValue];

    // do something with a and b
}


[[NSInvocationOperation alloc] 
    initWithTarget:self
          selector:@selector(myMethod:)
            object:[NSDictionary dictionaryWithObjectsAndKeys:
                     [NSNumber numberWithInt:123], @"A",
                     [NSNumber numberWithInt:456], @"B",
                     nil]];

NSInvocationOperation initWithInvocation example ios


initWithInvocation:

Returns an NSInvocationOperation object initialized with the specified invocation object.
- (id)initWithInvocation:(NSInvocation *)inv
Parameters
inv
The invocation object identifying the target object, selector, and parameter objects.
Return Value( NSInvocationOperation initWithInvocation example )
An initialized NSInvocationOperation object or nil if the object could not be initialized.
Discussion
This method is the designated initializer. The receiver tells the invocation object to retain its arguments.
( NSInvocationOperation initWithInvocation example )
#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSString *name;
    NSUInteger age;
}
- (void)setName:(NSString *)personName age:(NSNumber *)personAge;
@end

@implementation Person
- (void)setName:(NSString *)personName age:(NSNumber *)personAge {
    NSLog(@"setName:%@ age:%@", personName, personAge);
    name = [personName copy];
    age = [personAge unsignedIntegerValue];
}
@end

int main() {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];            
    Person *person = [Person new];

    SEL sel = @selector(setName:age:);

    NSMethodSignature *sig = [Person instanceMethodSignatureForSelector:sel];
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];

    [inv setTarget:person];
    [inv setSelector:sel];

    NSString *name = nil;
    NSNumber *age = nil;

    [inv setArgument:&name atIndex:2];
    [inv setArgument:&age atIndex:3];

    // [inv retainArguments];
    // [inv invoke];

    NSInvocationOperation *op = [[[NSInvocationOperation alloc] initWithInvocation:inv] autorelease];
    NSOperationQueue *queue = [NSOperationQueue new];
    [queue addOperation:op];

    [pool release];
    return 0;
}
( NSInvocationOperation initWithInvocation example )
NSInvocationOperation *load = [[NSInvocationOperation alloc] initWithInvocation:loadInvoc];
NSAssert([loadInvoc argumentsRetained],@"Arguments have not been retained");
[loader release];

NSInvocation *completionInvoc = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(serviceCompletionBlock:afterInvocationCompleted:)]];
[completionInvoc setTarget:self];
[completionInvoc setSelector:@selector(serviceCompletionBlock:afterInvocationCompleted:)];

MFEImageCallback callback = [completionBlock copy];

[completionInvoc setArgument:&callback atIndex:2];
[completionInvoc setArgument:&load atIndex:3];

NSInvocationOperation *completion = [[NSInvocationOperation alloc] initWithInvocation:completionInvoc];
NSAssert([completionInvoc argumentsRetained],@"Completion handler not retaining");
[callback release];
[completion addDependency:load];
( NSInvocationOperation initWithInvocation example )
- (void)fetchImageWithURLs:(NSArray *)urlArray {
    [self.retriveAvatarQueue cancelAllOperations];
    self.retriveAvatarQueue = nil;

    NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];

    for (NSUInteger i=0; i<[urlArray count]; i++) {
        NSURL *url = [urlArray objectAtIndex:i];

        NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(cacheImageWithIndex:andURL:)]];
        [inv setTarget:self];
        [inv setSelector:@selector(cacheImageWithIndex:andURL:)];
        [inv setArgument:&i atIndex:2];
        [inv setArgument:&url atIndex:3];

        NSInvocationOperation *invOp = [[NSInvocationOperation alloc] initWithInvocation:inv];
        [opQueue addOperation:invOp];
        [invOp release];
    }

    self.retriveAvatarQueue = opQueue;
    [opQueue release];
}

- (void)cacheImageWithIndex:(NSUInteger)index andURL:(NSURL *)url {
    NSData *imageData = [NSData dataWithContentsOfURL:url];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = PATH_FOR_IMG_AT_INDEX(index);
    NSError *error = nil;

    // Save the file      
    if (![fileManager createFileAtPath:filePath contents:imageData attributes:nil]) {
        DLog(@"Error saving file at %@", filePath);
    }

    // Notifiy the main thread that our file is saved.
    [self performSelectorOnMainThread:@selector(imageLoadedAtPath:) withObject:filePath waitUntilDone:NO];

}