Search code examples
objective-cnsmutabledata

Accessing NSMutableData from another class


Ok I have declared the NSMutableData in the .h of class 1 as followed

NSMutableData *dataResponse;

@property (strong, nonatomic) NSMutableData *dataResponse;

in the .m of class 1 I have @synthezie dataResponse, and then I am giving it some data in a function.

I want to access dataResponse in class 2 with that data that I have assigned to it in the function.

How can I get the data from dataResponse in class 2? Any help would be great.


Solution

  • You can use helper class for accessing array in different class. Create an NSObject file in the project. I've named it Passing Class

    In your PassingClass.h

    #import <Foundation/Foundation.h>
    
    @interface PassinClass : NSObject
    {
      NSMutableData *dataResponsetoPass;
    }
    +(PassinClass*)sharedString;
    
    
    -(void)setdataResponsetoPass:(NSMutableData*)data;
    -(NSMutableData*)getDataResponse;
    

    In your PassinClass.m

    #import "PassinClass.h"
    
    @implementation PassinClass
    @synthesize dataResponsetoPass;
    static PassinClass*sharedString;
    
    +(PassinClass*)sharedString
    {
     if(!sharedString)
     {
        sharedString=[[PassinClass alloc]init];
      }
    
      return sharedString;
    }
    
    
    -(void)setdataResponsetoPass:(NSMutableData*)data
    {
      dataResponsetoPass=data;
    }
    -(NSMutableData*)getDataResponse;
    {
       return dataResponsetoPass;
    }
    

    In your class1.h create instance of this helper class.

    #import "PassinClass.h"
    {
      PassinClass*pClass;
    }
    

    In your class1.m, set the data using

    pClass=[PassinClass sharedString];
    [pClass setdataResponsetoPass:Your Data];
    

    In your class2.m get the data using

    pClass=[PassinClass sharedString];
    [pClass getDataResponse];
    

    NSLog the [pClass getDataResponse ] to check, if everything went well you should be able to pass the response data from class 1 to class 2.