Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass delegate as a parameter objective-c

I am working with an NSOperationQueue and I want to add new NSOperations to the NSOperationQueue. It is a queue that lives in a singleton instance of a class I have. It would make things a lot easier if I could move everything into the static class by passing the delegate.

Here is my code now as it lives in - this is in a cellForRowAtIndexPath

 NSString *key = [NSString stringWithFormat:@"%@%@",cell.dataItem.ItemID, cell.dataItem.ManufacturerID];

        if (![self.imgOperationInQueue valueForKey:key]) {

            ImageOperation *imgOp = [[ImageOperation alloc] initWithItemID:cell.dataItem.ItemID withManufacturerID:cell.dataItem.ManufacturerID withReurnType:kThumbnail];
            imgOp.identifier = [NSString stringWithFormat:@"%i", cell.tag];
            imgOp.delegate = self;
            [[SharedFunctions sharedInstance] addImageOperationToQueue:imgOp];
            [imgOp release];

            // store these in the dictionary so we don;t queue up requests more than once
            [self.imgOperationInQueue setValue:cell.dataItem.ItemID forKey:key];
        }

If I could add the delegate as a parameter I could put all of this code into the shared singleton class and call it from anywhere in my app.

I suppose that I could use an NSNotification - or can I use a block of some sort?

like image 938
Slee Avatar asked Jun 13 '12 13:06

Slee


People also ask

How do you implement delegates in Objective-C?

An Objective-C delegate is an object that has been assigned to the delegate property another object. To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol.

How do you declare a protocol in Objective-C?

In Objective-C, you add the protocol name in angle brackets beside the class interface declaration. MyClass is declaring that it conforms to SampleProtocol below. MyClass will also have to provide an implementation for “someMethod” in the implementation file because it is a required protocol method.


1 Answers

Just create the appropriate init method that passes in the delegate.

- (id)initWithItemID:(NSString *)itemID
  withManufacturerID:(NSString *)manufacturerID
       withReurnType:(NSInteger)type
            delegate:(id<YourDelegate>)theDelegate
{
    self = [super init];
    if (self)
    {
        .... // Other assignments
        self.delegate = theDelegate;
    }

    return self;
}
like image 61
bbarnhart Avatar answered Sep 28 '22 01:09

bbarnhart