how to stop creating object Instance when its not need - iphone

The class do have
-(void) trackByPage : (NSString*) pageName {
TrackPage *track_p;
= [[TrackPage alloc] init];
track_p.page1 = #"welcome";
track_p.page2= self.String1;
[track_p release];
}
I am accessing from controller class this method.
- (void)viewDidLoad {
[super viewDidLoad];
TrackPageMeasurement *trackPage_Measurement = [[TrackPageMeasurement alloc]init];
[trackPage_Measurement trackByPage:#"Msg"];
[trackPage_Measurement release];
}
- (void)selectedDataValue {
TrackPageMeasurement *trackPage_Measurement = [[TrackPageMeasurement alloc]init];
[trackPage_Measurement trackByPage:#"DataValue"];
[trackPage_Measurement release];
}
I am accessing that through another class. trackByPage. by passing string ..
Each time i am accessing each time object instance is created how to stop those thing.

selectedDataValue shouldn't be calling [super viewDidLoad]; The code doesn't exactly inspire me with confidence; it looks to me more like that you want to retrieve some tracking object rather than creating a new one each time. Do you know what a singleton is?
Using a singleton would look more like:
TrackPage *track_p = [TrackPage instance];
track_p.page1 = #"welcome";
track_p.page2 = self.String1;

How about
TrackPage *track_p;
if(track_p==nil)
{
track_p= [[TrackPage alloc] init];
track_p.page1 = #"welcome";
track_p.page2= self.String1;
}
[track_p release];

Related

SAFELY_RELEASE in ViewDidUnLoad

is there any difference between the two methods?
```
// MACRO FUNCTION
#define SAFELY_RELEASE(__POINTER) { [__POINTER release]; __POINTER = nil; }
// C FUNCTION
void SAFELY_RELEASE(id __POINTER) {
[__POINTER release]; __POINTER = nil;
}
```
Yes. The function won't do what you expect it to, because the pointer will have been passed into it by value, rather than by reference.
Imagine this:
- (void)method {
id object = [[NSObject alloc] init];
SAFELY_RELEASE( object );
}
SAFELY_RELEASE gets object. It can send it messages, but setting it to nil will not change its value in method.
An equivalent function would be:
void SAFELY_RELEASE(id *__POINTER) {
[*__POINTER release]; *__POINTER = nil;
}
Then you'd use it by using:
SAFELY_RELEASE( &object );
The macro has another downside, though: Xcode's refactoring tools will probably not be able to change the parameter inside. For instance:
#interface Foo {
NSObject *var;
}
#implementation Foo
- (id)init {
if (( self = [super init] )) {
var = [[NSObject alloc] init];
}
return self;
}
- (void)dealloc {
SAFELY_RELEASE(var);
[super dealloc];
}
If you try to rename var using the refactor tool, you'll probably find that it won't be able to rename the var in dealloc.
Really, unless you have a really good reason to do this you should be using ARC.
void SAFELY_RELEASE(id __POINTER) is guaranted to __POINTER be an releasable object.
Both of them is wrong, because __POINTER = nil; will have no effects. You should nil it in object (controller)
I was using one of these macros, then I cam across this post.
Makes sense that you don't want to set to nil while in development as you want it to crash on a dealloc reference and not sending it to nil.

Dropbox Api in iphone

I am trying to integrate dropbox with iphone and done with login option.I want to load folders and files on root path in table view just after login.
code for this is
- (void)viewWillAppear:(BOOL)animated {
[self.restClient loadMetadata:#"/"];
}
This loadMetadata is method in DBRestClient.m class.I managed to print json value on console
Code is
- (void)parseMetadataWithRequest:(DBRequest*)request {
NSAutoreleasePool* pool = [NSAutoreleasePool new];
NSDictionary* result = (NSDictionary*)[request resultJSON];
DBMetadata* metadata = [[[DBMetadata alloc] initWithDictionary:result] autorelease];
[self performSelectorOnMainThread:#selector(didParseMetadata:) withObject:metadata waitUntilDone:NO];
NSLog(#"Meta data is :%#",result);
[pool drain];
}
How could I use this result value in my view controller to display this in tableview?
Get the contents of a directory and put them into an array.
- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata
{
for (DBMetadata* child in metadata.contents)
{
if (child.isDirectory)
{
[self.restClient loadMetadata:child.path withHash:hash];
}
else
{
if ( [self.directory isEqualToString:#"a directory"] ) {
/* child.path is the file, so put it into an array */
}
}
}
}
Than load your array into your UITableView as you would any other NSArray / NSMutableArray

TTPostController - Keyboard is not appearing

Hi
I am adding a "post comment section in my iPhone APP"
rest all things are working fine but when I tap on "postController textView" a keyboard is suppose to appear from the bottom but it is not appearing However the cursor is displaying and the text that I am passing using postController.textView.text = #"" is also displaying.
Please suggest the areas to be looked for fixing this bug.
-(void)showCommentView
{
TTPostController *postController = [[TTPostController alloc] init];
// self must implement the TTPostControllerDelegate protocol
postController.delegate = self;
self.popupViewController = postController;
// assuming self to be the current UIViewController
postController.superController = self;
postController.textView.text=#"temporary text";
[postController showInView:self.view animated:YES];
[postController release];
}
above is the code that is giving call to the Three20 PostController
below is the calling method which is unchanged...
-(IBAction)postComment:(id)sender
{
[UserManager instance]authenticateUserAndProceed:self withSelector:#selector(showCommentView)];
}
-(void)showCommentView
{
TTPostController *postController = [[TTPostController alloc] init];
// self must implement the TTPostControllerDelegate protocol
postController.delegate = self;
self.popupViewController = postController;
// assuming self to be the current UIViewController
postController.superController = self;
postController.textView.text=#"temporary text";
[postController showInView:self.view animated:YES];
[postController release];
}
changed method
-(void)authenticateUserAndProceed:(id)parent withSelector:(SEL)selector
{
theParentViewController = parent;
self.theFunctionToCall = selector;
if(userid == nil)
{
GetUserInfoViewController *guivc = [[GetUserInfoViewController alloc] init];
[parent presentModalViewController:guivc animated:YES];
guivc.delegate = self;
[guivc release];
}
else {
//////////////////// below line was replaced///////////
// 2. [theParentViewController performSelector:selector];
// with below code
UIAlertView *alert =[[UIAlertView alloc]initWith Title........
[alert show];
}
}
PROBLEM SUMMARY:
as soon as the user registered, he was not able to the kyboard for the TTPostController
CHANGE SUMMARY:
As soon as the user is registered the call to
[theParentViewController performSelector:selector];
is not sent directly but the call goes to ann alertview which inter calls it.
EFETCS SUMMARY:
the user will see a "you are registered successfully" (kind of) alertview.
tapping OK on which, he will be sent to TTPostController. (this time the keyboard is appearing)
I kept the line# 2 in the AlertViewDelegate method.
I was amazed o see it working just by not calling the line 2 directly.
this worked for me.
I welcome any new and better idea to implement the same

RestKit with Three20 Integration

I'm trying to work with Restkit to call my web server api, but things are not working.
My controller just show the activity indicator and nothing happens.
I have an api call which suppose to return the top 50 videos ,for example:
http://example.com/services/getTop50Video
The return is in the format of :
<results>
<mysql_host>72.9.41.97</mysql_host>
<results>
<title/>
<views/>
<video_id>j2xFxHgENt4</video_id>
<thumbnail>http://img.youtube.com/vi/j2xFxHgENt4/2.jpg</thumbnail>
<url/>
</results>
...
</results>
My App delegate Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Configure RestKit Object Manager
RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:#"http://example.com/services"];
RKObjectMapper* mapper = objectManager.mapper;
[mapper registerClass:[YouTubeVideo class] forElementNamed:#"video"];
// Other non relevant stuff
}
TWYouTubeVideo Class :
#implementation TWYouTubeVideo
#synthesize title = _title;
#synthesize numberOfViews = _numberOfViews;
#synthesize videoID = _videoID;
#synthesize thumbnailURL = _thumbnailURL;
+ (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithKeysAndObjects:
#"title", #"title",
#"views", #"numberOfViews",
#"video_id", #"videoID",
#"thumbnail", #"thumbnailURL",
nil];
}
My Controller code :
-(id) initWithResourcePath:(NSString*) requestedResourcePath
{
if (self = [super init])
{
self.resourcePath = requestedResourcePath;
}
return self;
}
- (void)createModel {
self.model = [[[RKRequestTTModel alloc] initWithResourcePath:self.resourcePath] autorelease];
}
- (void)didLoadModel:(BOOL)firstTime {
[super didLoadModel:firstTime];
RKRequestTTModel* model = (RKRequestTTModel*)self.model;
NSMutableArray* items = [NSMutableArray arrayWithCapacity:[model.objects count]];
for (YouTubeVideo* video in model.objects) {
TableSubtitleItem *item = [TableSubtitleItem itemWithText:video.title
subtitle:[NSString stringWithFormat:#"%# views", video.numberOfViews]
imageURL:video.thumbnailURL
defaultImage:[YouTubeVideo defaultThumbnail]
URL:nil
accessoryURL:nil];
[items addObject:item];
}
// Ensure that the datasource's model is still the RKRequestTTModel;
// Otherwise isOutdated will not work.
TTListDataSource* dataSource = [TTListDataSource dataSourceWithItems:items];
dataSource.model = model;
self.dataSource = dataSource;
}
And pushing the Controller:
SecondYouTubeController* viewController = [[SecondYouTubeController alloc] initWithResourcePath:#"/getTop50VideoXML?json=true"];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
First, I guess I need to somehow tell the parser that the video objects appear inside a "response" node.
Second, I'm not sure I'm doing all the calls as should.
I would really appreciate help here.
You can drill down into the "responses" element by setting the keyPath property on your RKRequestTTModel to "responses".
Is your response actually XML? Currently RestKit doesn't support XML payloads (it's on the roadmap to get working again). Can you get a JSON payload? If not, and you feel like fighting the good fight, all you need to do is implement the RKParser protocol that can turn XML to/from Cocoa objects (Dictionaries and Arrays).
I found this question looking to get XML working with RestKit 0.20.
At the time of the answer above it wasn't possible - it now is via an additional module:
https://github.com/RestKit/RKXMLReaderSerialization
You can make use of it by adding this to your Podfile:
pod 'RKXMLReaderSerialization', :git => 'https://github.com/RestKit/RKXMLReaderSerialization.git', :branch => 'master'
And registering it for use thus:
[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:#"application/xml"];

Problem initializing an object with init in Objective-C

I have an object that i intalize it's propertis with call to an init function, it works fine,
when i tried to add another object and intalize it the first object didn't get the properites, how do i initalize it to more then one object with diffrent or the same properties?
- (void)viewDidLoad {
pic1 = [[peopleAccel alloc] init];
}
Class peopleAccel:
- (id) init
{
self = [super init];
if (self != nil) {
position = CGPointMake(100.0, 100.0);
velocity = CGPointMake(4.0, 4.0);
radius = 40.0;
bounce = -0.1f;
gravity = 0.5f;
dragging = NO;
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
acceleratedGravity = CGPointMake(0.0, gravity);
}
return self;
}
I see a problem with setting the delegate of sharedAccelerometer. Only one object can be a delegate of another object at a time. So you should create only one peopleAccel object.
EDIT:
If you need to send accelerometer events to more than one object, you can create a specific delegate object in charge of receiving accelerometer events and broadcasting them to your several peopleAccel objects via notifications. See this question for some hints: NSNotificationCenter vs delegation?
Create a proxy so multiple objects can receive accelerometer events.
Whether you should do this or use NSNotificationCenter is debatable and there are two camps, but personally I would use this approach. NSNotificationCenter has to check string names to recognise event type; this kind of approach could be ever so slightly faster especially with a bit more optimisation. A bit more typing but I would say also easier for someone else to follow.
Something like this...
/* PLUMBING */
/* in headers */
#protocol MyAccelSubDelegate
-(void)accelerometer:(UIAccelerometer*)accelerometer
didAccelerate:(UIAcceleration*)acceleration;
#end
#interface MyAccelSubDelegateProxy : NSObject <UIAccelerometerDelegate> {
NSMutableArray subDelegates;
}
-(id)init;
-dealloc;
-(void)addSubDelegate:(id<MyAccelSubDelegate>)subDelegate;
-(void)removeSubDelegate:(id<MyAccelSubDelegate>)subDelegate;
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
(UIAcceleration *)acceleration;
#end
/* in .m file */
#implementation MyAccelSubDelegateProxy
-(id)init { self = [super init];
if (self!=nil) subDelegates = [[NSMutableArray alloc] init]; return self; }
-dealloc { [subDelegates release]; }
-(void)addSubDelegate:(id<MyAccelSubDelegate>)subDelegate {
[subDelegates insertObject:subDelegate atIndex:subDelegates.count]; }
-(void)removeSubDelegate:(id<MyAccelSubDelegate>)subDelegate {
for (int c=0; c < subDelegates.count; c++) {
id<MyAccelSubDelegate> item = [subDelegates objectAtIndex:c];
if (item==subDelegate) { [subDelegates removeObjectAtIndex:c];
c--; continue; }
}
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
(UIAcceleration *)acceleration {
for (int c=0; c < subDelegates.count; c++)
[((id<MyAccelSubDelegate>)[subDelegates objectAtIndex:c])
accelerometer:accelerometer didAccelerate:acceleration];
}
#end
/* SOMEWHERE IN MAIN APPLICATION FLOW STARTUP */
accelProxy = [[MyAccelSubDelegateProxy alloc] init];
[UIAccelerometer sharedAcclerometer].delegate = accelProxy;
[UIAccelerometer sharedAcclerometer].updateInterval = 0.100; // for example
/* TO ADD A SUBDELEGATE */
[accelProxy addSubDelegate:obj];
/* TO REMOVE A SUBDELEGATE */
[accelProxy removeSubDelegate:obj];
/* SOMEWHERE IN MAIN APPLICATION SHUTDOWN */
[UIAccelerometer sharedAcclerometer].delegate = nil;
[accelProxy release];