override classes variable, or at least variable type in objective-c / cocoa - overriding

My dilemma is as follows:
I have a custom subclass of UIImage (I've added some serialization methods i.e. initWithCoder, encodeWithCoder), and I would like to apply my custom subclass as a variable to a UIImageView, or at least a subclass of UIImageView.
As you are aware, UIImageView has a variable called "image", that is of type UIImage. I'd like to override this variable with my subclass.
My goal is to have a UIimageView that will respond to archivedDataWithRootObject without crashing with the encodeWithCoder message is sent to the variable image. If there is a smarter way to get there, I'm open to suggestions.
Thank you!
[edit] I think one possible route is through some type of casting...However:
UIImage *image = [[UIImage alloc] init];
MLImage *mlImage = [[MLImage alloc] init];
mlIamge = (MLImage*)image;
When I mouse-over mlImage after the second line executes, I can see that it is of type MLImage. However, even with the cast, after the third line executes mlImage becomes a UIImage. What do I need to do to change the type of image to MLImage?
[/edit]

Be careful with your terminology. It's not possible to override a property—the UIImageView will still have its own image property, it won't be replaced. You're trying to override the accessors (-image and -setImage:).
And you're right, casting is a better route. But your example has a problem: that cast is illegal. When you do [[UIImage alloc] init], you're creating an object of type UIImage. Nothing is going to change that, including your cast. Casting is a way of telling the compiler (in your case) "I know you think that this UIImage* is, well, a UIImage, but it's really a MLImage." In this case, that's a lie, since it really is a UIImage—you allocated it right there.
What you can do, though, is stick an actual MLImage into the image property of a UIImageView. For example:
MLImage *myImage = [[MLImage alloc] init];
myView.image = myImage;
And then somewhere else:
MLImage *myImage = (MLImage *)(myView.image);
And you'll get back your custom image object. But it has to have been an MLImage in the first place.

Related

customizing Kal Calendar event

I am using storyboard and kal calendar controller, I want to customize the event of choosing one day on the calendar. By default when you choose one day events on that day appears in the table view under the month calendar. What i am trying to do is when choosing one day another view controller is showing up and it is filtered on the day chosen.
Until now I founded where I should edit. But I can't call the other view to show up !!
I tried this but it dose not work !!
tableViewController *tbl = [[tableViewController alloc] initWithNibName:#"menuView" bundle:nil];
[self dismissViewControllerAnimated:YES completion:nil];
I found this but I do not know how to use it and if it is helpful for me or not .. any help ?
UIStoryboard* sb = [UIStoryboard storyboardWithName:#"menuView" bundle:nil];
tableViewController *vc = [sb instantiateViewControllerWithIdentifier:#"menuView"];
The second batch of code in your question is headed in the right direction, but not exactly right.
First, you want to get an instance of your project's storyboard. That's what you're attempting to do in the first line of code. However, I believe you're referring to your storyboard by the wrong name. Usually Xcode defaults the name of storyboards to 'MainStoryboard.storyboard', while you're trying to refer to it as 'menuView'. So you'll want to change that first line of code to this:
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
Next, you need a way to refer to the ViewController you want in the Storyboard. That's what you're attempting in the second line of code. You need to make sure you're getting a proper reference to it:
In your storyboard, select the ViewController you're wanting to show up
In the Identity inspector, enter "tableViewController" in the Class field
Enter "menuView" in the Storyboard ID field
Finally, you'll need to add one line of code to actually present the ViewController.
So all in all your code should look something like this:
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
tableViewController *vc = [sb instantiateViewControllerWithIdentifier:#"menuView"];
[self presentViewController:vc animated:YES completion:nil];

Unable to update table in superview from subview

I am using Xcode 4.3 and am somewhat of a nubbie in Xcode although I have been a programmer for many years.
I have a UIView called First that contains a UITable that gets its contents from files in memory. I then create a subview UIView called Second that makes changes in the data files that should change the contents of the table in First. When I remove Second and return to First, not surprising, the table is not updated. The next time First is loaded from the start, the table reflects the changes that were made.
First contains the method viewDidLoad which is used to load an NSArray from data in files with the data needed by the table. I am able to call viewDidLoad from Second but unless the table is updated from the newly changed NSArray the table will appear as it did before the changes were made.
So my problem is how to call a table method from Second so that the table in First is updated when I remove Second and return to First. I have tried calling the table method that loads the data into the table but have been unsuccessful since I get compile errors. I need to know how to call the table function in a way that will result in the table being updated when I return to first.
At least part of my problem is I don't know how the table update is called since it is not called from viewDidLoad as I might have expected.
Sorry, it is a long winded description of the problem. Much of the rest of the program that I am writing is working and I have been dealing with this issue for several months. I return every few weeks and take another stab at it but no luck so far. I really would appreciate any help you can give that will improve my understanding and fix the problem.
Here is the code after the fix: first (superview) pertinent code
-(void)viewDidLoad {
NSFileManager * fm = [[NSFileManager alloc] init];
NSError* err = nil;
NSPredicate *fltr = [NSPredicate predicateWithFormat:#"self ENDSWITH '.dir'"];
NSArray *array = [fm contentsOfDirectoryAtPath: userFolder error:&err];
self.listData = [array filteredArrayUsingPredicate:fltr];
[self.tableView reloadData]; //This does the updating must make table an IBOutlet as
[super viewDidLoad]; //described in one of the comments by m. Othman
}
Here is the code after the fix: second (subview) pertinent code. This code located
in the method where changes are made that should effect the table display
UIView * start = [self.view superview]; //this line and next two call viewDidLoad in first
UIResponder * nextResponder = [start nextResponder];
[nextResponder viewDidLoad];
Have you read the UIViewController API reference? There are more options beyond -viewDidLoad for dealing with the (re)appearance of a view...
well, UITableView Delegates called just on the loading of the view or when you ask it to reload ..
so in your viewDidLoad or any method that should changes the content of the tableview , you need to write this line
[tableview reloadData];
I hope I understand your question!!

NSString - stringWithFormat released automatically

#property(nonatomic, retain) NSString *password;
-(id)init {
...
password=[NSString stringWithFormat:#"%#", [[NSProcessInfo processInfo] globallyUniqueString]];
OR
password=[[NSProcessInfo processInfo] globallyUniqueString];
}
My problem is that during course of execution at some random point the password object gets automatically released. Effect is same when i use either of the assignments. As soon as i put in a retain, the problem no longer exists. I'm sure there is no release of password object anywhere in the flow - as i mentioned it is in a singleton class. I also checked that the class instance is same even when the password object is released.
Any hints please!
You assign the iVar, not the property...
So as you don't use the setter method, your object is not retained.
Use the property instead:
self.password = ...
You could use...
password=[[NSString stringWithFormat:#"%#", [[NSProcessInfo processInfo] globallyUniqueString]] retain];
Also checkout Apple's doc on memory management. I would also set breakpoints in your code and see then your object gets released.

Create outlets and code programatically in XCode

I find it very tedious having to create connections and other repeatable stuff in XCode 4. This just does not seem RAD to me. Let me explain
I have a View based iPad project with a single view.
On the view are about 50 buttons and 50 UIImage objects - total 100 objects. All the UIImage objects have the same image. All the buttons have the same Action. The tag of each button determines the code to run in the Action.
What I find tedious is:
I have to type in a "tag" for each of the objects - 100 tags
I have to drag each object to make an outlet which produces code like this in the .h file:
#import <UIKit/UIKit.h>
#interface bbTestViewController : UIViewController {
UIImageView *pop1;
UIImageView *pop2;
UIImageView *pop3;
UIImageView *pop4;
UIImageView *pop5;
etc....
for the 50 controls and also this code below:
#property (nonatomic, retain) IBOutlet UIImageView *pop1;
#property (nonatomic, retain) IBOutlet UIImageView *pop2;
#property (nonatomic, retain) IBOutlet UIImageView *pop3;
#property (nonatomic, retain) IBOutlet UIImageView *pop4;
#property (nonatomic, retain) IBOutlet UIImageView *pop5;
etc....
for the 50 controls.
and in the .m file:
#synthesize pop1;
#synthesize pop2;
#synthesize pop3;
#synthesize pop4;
#synthesize pop5;
etc.....
This also adds lines like this:
- (void)viewDidUnload
{
[self setPop1:nil];
[self setPop2:nil];
[self setPop3:nil];
[self setPop4:nil];
[self setPop5:nil];
etc.....
and
- (void)dealloc {
[pop1 release];
[pop2 release];
[pop3 release];
[pop4 release];
[pop5 release];
etc.....
3.Then for each of the 50 buttons I have to drag them to the the same Action to make the connection, select the touch action, type a name and then click OK.
This I find tedious and counter productive. Not RAD at all. More SAD. So much of repeating the same actions, it is painful.
So the Question is, is there an easier way. I do not believe in Copy/Paste so that solution is a no-no.
In other languages I would use a For...Each to iterate thru every object and do the needful.
e.g. for the tag:
I would have code to set the tags like this:
Integer n = 1;
For Each oObject in myView
oObject.tag = n
n = n+1
end for
So can I use code to get around these tedious processes of
tag
Declaring each object and adding the #property... code
adding the #synthesize... code
setting each object to nil
releasing each object
Somehow automate the connection from all the buttons to the Action.
I want to be able to do all this in code and without all that copy/paste stuff or those repeatable actions in IB for XCode 4 by dragging to make a connection.
Is this at all possible in this MVC system that XCode 4 uses? If so, how?
Update
After some research I found at least one answer to my Q - with regard to Connections to Actions.
It appears that if you add an object - say a button and make a connection to an action in IB, then if you copy and paste that button (or any such object), IB RETAINS the connections made so in my case above, I create the button and make the connection to the Action and if I copy and paste it, IB will make the connections to the same Action for every pasted button. At least that will save some time. HTH others.
You are right about one thing IB sucks royally. I had high hopes that Apple would have done more to fix it in XCode 4.x.
However I do wonder about your interface. Having 50 buttons on one view seems to be a little much. So you might want to refactor that aspect of your project.
As to your current issue, do realize that you can build an app without IB. You do need to learn how to programiclly build the controls and do the layout. I'd suggest looking at sample code from Apple first.
Still I'd suggest thinking long and hard about those 50 buttons.
In the view controller do:
for (int i = 0; i < 50; i++) {
UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
xpos = ...; // appropriate coordinate go here
ypos = ...; // appropriate coordinate go here
[button setFrame: CGRectMake(xpos, xpos, buttonWidth, buttonHeight)];
[button addTarget: self action: #selector(myCoolAction:) forControlEvents: UIControlEventTouchUpInside];
[button setTag: i];
[[self view] addSubview: button];
}
and you should be fine. Same for the images...
there is a sort of halfway house approach that i have used in one of my apps, where i wanted to be able to address buttons in a grid using an array in code, and like you, i wanted to design the look and feel in IB.
i did what you did in the sense that i put all the buttons on the view, and went as far as declaring an ivar, #property and #synhesize declaration for each one. since they were in a grid like you have described, what i did was name each one along the lines of button_1x1 button_1x2 etc (ie button_rxc as row x column if you think of a spreadsheet. the names are not important as you are only ever going to refer to them once in a method you call from viewDidLoad.
in that method, i created a bunch of NSArrays that held each button. for example:
landscapeHidden = [[NSArray arrayWithObjects:
button_3x1, button_3x2,
button_4x1, button_4x2,
nil] retain];
portraitHidden = [[NSArray arrayWithObjects:
button_1x3, button_1x4,
button_2x3, button_2x4,
nil] retain];
landscapeButtons = [[NSArray arrayWithObjects:
button_1x1, button_1x2, button_1x3, button_1x4,
button_2x1, button_2x2, button_2x3, button_2x4,
nil] retain];
portraitButtons = [[NSArray arrayWithObjects:
button_1x1, button_1x2,
button_2x1, button_2x2,
button_3x1, button_3x2,
button_4x1, button_4x2,
nil] retain];
i then used these arrays whenever i wanted to iterate them programatically.
the _hidden arrays are just used to indicate what buttons to hide when the display changes perspective - rather than move them around i figured it was faster to just hide the few that did not fit, and repaint them all.
as for interface builder, try this:
hold down control and click "File's Owner" once, and wait.
you will then get a large panel that you can use to wire connections to the view objects. i prefer using this method regardless of which direction i am connecting things up - ie if you drag from the objects directly the direction you drag in is not always convenient. this way you can easily view all the outlets at once. much easier from my perspective.
having said that it's pretty easy to loop through an array and assign targets or add gesture recognizers/ update titles/ colors/ whatever you like. i suppose you could also store them in a dictionary, (or have an array of dictionaries).
i went the array of having an array of dictionaries and the arrays of buttons you see above. on interface flips, the dictionaries don't change, but the buttons in the arrays get re-tagged, so any methods that have them as a "sender" can immediately get their dictionary data by indexing into the data array with
[myArray objectForIndex: ((UIButton*)sender).tag];
another trick - cmd-b build before you try doing anything in IB. this ensures it picks up things you have just edited, or files you have just added. sometimes i have had to clean/build to force an image to appear in the IB drop-downs. it's usually pretty good, but if you rename an image file, it's usually easier to delete it from the project and drag it in again, build (or clean build) then it should be good to go.

Initializing multiple subclassed sprites of the same kind in Cocos2D from Tiled

I'm trying to figure out the best way to initialize multiple sprites placed in Tiled that are the same type. I don't even know really how to start off in Tiled, because I'm only used to initializing one sprite by filling out the name field, and then in my CCLayer with the map I do something like
CCTMXObjectGroup *objects = [theMap objectGroupNamed:#"oj"];
NSMutableDictionary *startPoint = [objects objectNamed:#"StartPoint"];
int x = [[startPoint valueForKey:#"x"] intValue];
int y = [[startPoint valueForKey:#"y"] intValue];
hero = [[HeroClass alloc] init];
[self addChild:hero.heroSpriteSheet];
hero.heroSprite.position = ccp(x,y);
As you can see, my "hero" is subclassed, and this goes for another sprite that is a bird, but I want an x amount of them. I import the header of HeroClass and create a pointer, make a property and synthesize that in my main file and finally release HeroClass in dealloc. I have a feeling that I will most likely end up use NSMutableArray, but I don't really know how in the case of subclassing. Also I'm not sure if I'll be using objectNamed:#"name" because I'll have x number of these sprites that I will be just duplicating throughout Tiled.
There's a helpful post here that shows how to add multiple sprites, but I don't know how to relate it to Tiled or subclassing:
http://www.iphonedevsdk.com/forum/iphone-sdk-game-development/58334-adding-sprites-screen-when-detecting-tap-cocos2d.html
Does anyone have any useful pointers or code examples relating how to resolve my issue? Thanks!
TLDR:
How do I initialize sprites from the same class in a CCLayer (that renders my map and other sprites) based upon definite object locations that were placed in a Tiled TMX map?
I'd suggesting creating an enemy class. Then, you create a bunch of them using a for loop. As far as spawnpoints, you would have each enemy set its own spawn point up based on rules. (Map borders, "safe areas", etc.)

Resources