Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

NorthKyut

macrumors newbie
Original poster
Aug 20, 2010
4
0
Dear all,

Hi, I am a newbie of xcode and objective-c and I have a few questions regarding to the code sample of a game attached below. It is written in objective C, Xcode for iphone4 simulator. It is part of the code of 'ball bounce against brick" game. Instead of creating the image by IB, the code supposes to create (programmatically) 5 X 4 bricks using 4 different kinds of bricks pictures (bricktype1.png...). I have the bricks defined in .h file properly and method written in .m.

My questions are for the following code:
Code:
- (void)initializeBricks
{ 
	brickTypes[0] = @"bricktype1.png";
	brickTypes[1] = @"bricktype2.png";  
	brickTypes[2] = @"bricktype3.png";  
	brickTypes[3] = @"bricktype4.png";  
	int count = 0;
	for (int y = 0; y < BRICKS_HEIGHT; y++)  
	{  
		for (int x = 0; x < BRICKS_WIDTH; x++)  
		{   
Line1 --        UIImage *image = [ImageCache loadImage:brickTypes[count++ % 4]];  
Line2 --        bricks[x][y] = [[[UIImageView alloc] initWithImage:image] autorelease]; 
Line3 --        CGRect newFrame = bricks[x][y].frame;  
Line4 --        newFrame.origin = CGPointMake(x * 64, (y * 40) + 50);  
Line5 --        bricks[x][y].frame = newFrame;
Line6 --        [self.view addSubview:bricks[x][y]]
		}  
	}  
}
1) When it is compiled, error "ImageCache undeclared" in Line 1. But I have already added the png to the project. What is the problem and how to fix it? (If possible, please suggest code and explain what it does and where to put it.)

2) How does the following in Line 1 work? Does it assign the element (name of .png) of brickType to image?

>brickTypes[count ++ % 4]

For instance, returns one of the file name bricktype1.png to the image object? If true, what is the max value of "count", ends at 5? (as X increments 5 times for each Y). But then "count" will exceed the max 'index value' of brickTypes which is 3!

3) In Line2, does the image object which is being allocated has a name and linked with the .png already at this line **before** it is assigned to brick[x][y]?

4) What do Line3 and Line5 do? Why newFrame on left in line3 but appears on right in Line5?

5) What does Line 4 do?
 

Attachments

  • Screen shot 2010-08-21 at 7.59.50 PM.jpg
    Screen shot 2010-08-21 at 7.59.50 PM.jpg
    249.7 KB · Views: 112

chown33

Moderator
Staff member
Aug 9, 2009
10,750
8,422
A sea of green
Where did you get the code? Is it from a book or tutorial?

If so, then it should explain the code.

If it's not from a book or tutorial, then the author probably assumes you know enough Objective-C and Cocoa to make sense of the code. If you don't know enough, then you should start with a book or tutorial.


Do you know any other programming languages, or is this your first?
I could probably guess the answer, but it's better if you describe your experience.


I will try to briefly answer your questions. If the answers don't make enough sense, then you should get a book or online tutorial and learn the fundamentals. Because the long explanation would take many pages, literally enough to fill a book.

1) When it is compiled, error "ImageCache undeclared" in Line 1. But I have already added the png to the project. What is the problem and how to fix it? (If possible, please suggest code and explain what it does and where to put it.)
The problem has nothing to do with any png. ImageCache is an unknown variable or class name. The problem is it needs to be declared or defined first.

There is no way to tell you how to fix it. We'd have to know where the code came from, so we could see the entire program.


2) How does the following in Line 1 work? Does it assign the element (name of .png) of brickType to image?

>brickTypes[count ++ % 4]

For instance, returns one of the file name bricktype1.png to the image object? If true, what is the max value of "count", ends at 5? (as X increments 5 times for each Y). But then "count" will exceed the max 'index value' of brickTypes which is 3!

You have multiple questions there.

a) It takes the value of count, increments the variable, then calculates the modulus (remainder after division). That's used as a subscript in the brickTypes array.

b) No. The string is passed to another object, which returns an image. That image is assigned.

c) The % 4 applies the modulo operator. It prevents the value from reaching or exceeding 4.
http://en.wikipedia.org/wiki/Modulo_operation


3) In Line2, does the image object which is being allocated has a name and linked with the .png already at this line **before** it is assigned to brick[x][y]?

An image isn't being allocated, a UIImageView is. The image was loaded from the png in line 1, by the undeclared ImageCache. This line puts the image in a view and stores it in the bricks matrix.


4) What do Line3 and Line5 do? Why newFrame on left in line3 but appears on right in Line5?

Line 3 declares a rectangle and assigns the frame of a brick to it.
Line 5 assigns a rectangle to the frame of a brick.
The expression on the right of the = is assigned to the value on the left. That's how assignment works.
http://en.wikipedia.org/wiki/Assignment_(computer_science)


5) What does Line 4 do?

It calculates and assigns a new origin to newFrame.
 

lloyddean

macrumors 65816
May 10, 2009
1,047
19
Des Moines, WA
He seems to be trying to modify code found in the title "Beginning iPhone Games Development" published by APress, ISBN-13 (pbk): 978-1-4302-2599-7.

The original code in question first appears in Listing 3-24 on page 60 and he appears to be trying to modify it to make use of a custom image caching class introduced on page 71 in listings 3-32 and 3-33.
 

NorthKyut

macrumors newbie
Original poster
Aug 20, 2010
4
0
Reply and more questions on the topics...

Thanks for chown33 details explanation and everything makes sense now exception for Line 3 and Line5. I understood both are doing assigning tasks but the thing I don't understand is Line3 has already declared a rectangle and assigns the frame of a brick to it but why Line5 assigns a rectangle back to the frame?

Thanks for lloyddean information and he is right, it is sample code from the book that he mentioned. I haven't modified the code at all.

In fact, I just want to understand and run it. But on and before page 60, there isn't mentioned how to declare the code imagecache at all. And on page 71, it just simply gives me the modified code as below. I have no idea what they mean at all and I even don't know how to create the ImageCache.h and ImageCache.m files at all in the Xcode. Could you explain the following and explain how it works? Can I simply declare in the .h file without doing any modification in .m and makes the code compile? Please advise me. I don't want to get stuck at this point.

Really appreciated any help from you folks.


Code:
#import <Foundation/Foundation.h>  

@interface ImageCache : NSObject {

}

+ (UIImage*)loadImage:(NSString*)imageName;
+ (void)releaseCache;

@end`
----------------------------------------------------------
#import "ImageCache.h"

@implementation ImageCache

static NSMutableDictionary *dict;

+ (UIImage*)loadImage:(NSString*)imageName
{
	if (!dict) dict = [[NSMutableDictionary dictionary] retain];
	
	UIImage* image = [dict objectForKey:imageName];
	if (!image)
	{
		NSString* imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];	
		image = [UIImage imageWithContentsOfFile:imagePath];
		if (image)
		{
			[dict setObject:image forKey:imageName];
		}
	}
	
	return image;
}

+ (void)releaseCache {
	if (dict) {
		[dict removeAllObjects];
	}
}

@end
 

chown33

Moderator
Staff member
Aug 9, 2009
10,750
8,422
A sea of green
Thanks for chown33 details explanation and everything makes sense now exception for Line 3 and Line5. I understood both are doing assigning tasks but the thing I don't understand is Line3 has already declared a rectangle and assigns the frame of a brick to it but why Line5 assigns a rectangle back to the frame?

What does it mean to assign something? To change it.
What is being assigned to the brick view's frame? A changed rectangle.
So the code in 3-5 is changing the brick view's frame, using a temporary rectangle variable for the calculation.

Why is it changing the brick view's frame? Look at the calculation.
Walk through the calculation manually with a few values of x and y.
After the whole loop has run, what is the geometric layout of all brick view frames?


The book has a website:
http://playcontrol.net/iphonegamebook/

That website has a forum. I suggest asking your questions about the book there. I don't have the book, so I can't tell you how to make the code work.

The website also has an Errata section that lists errors in the book.
 

dejo

Moderator emeritus
Sep 2, 2004
15,982
452
The Centennial State
And on page 71, it just simply gives me the modified code as below. I have no idea what they mean at all and I even don't know how to create the ImageCache.h and ImageCache.m files at all in the Xcode.
If you don't know how to create a new class in Xcode, you're in over your head at this point. Step away from the real coding and go (re)learn the basics of Objective-C programming.
 

NorthKyut

macrumors newbie
Original poster
Aug 20, 2010
4
0
What does it mean to assign something? To change it.
What is being assigned to the brick view's frame? A changed rectangle.
So the code in 3-5 is changing the brick view's frame, using a temporary rectangle variable for the calculation.

Why is it changing the brick view's frame? Look at the calculation.
Walk through the calculation manually with a few values of x and y.
After the whole loop has run, what is the geometric layout of all brick view frames?


The book has a website:
http://playcontrol.net/iphonegamebook/

That website has a forum. I suggest asking your questions about the book there. I don't have the book, so I can't tell you how to make the code work.

The website also has an Errata section that lists errors in the book.

So Newframe is an object and works like variable this case? First, bracks[x][y].frame's info is copied to Newframe and after Newframe's origin information is updated, all info is copied back to bracks[x][y].frame. If that is true, why can't just directly update bracks[x][y] location?
 

chown33

Moderator
Staff member
Aug 9, 2009
10,750
8,422
A sea of green
So Newframe is an object and works like variable this case? First, bracks[x][y].frame's info is copied to Newframe and after Newframe's origin information is updated, all info is copied back to bracks[x][y].frame. If that is true, why can't just directly update bracks[x][y] location?

First, the newFrame variable is NOT an object. It's a CGRect, which is not an object.

Second, try rewriting the code without a temporary variable. See what it looks like. Is it clear what the code is doing?

Third, you've mistakenly called the array bracks, instead of bricks, and the temp variable Newframe instead of newFrame. Ordinarily I wouldn't bother correcting anyone's spelling or capitalization, but precision and clarity are crucial in programming, and Objective-C is case-sensitive.
 

NorthKyut

macrumors newbie
Original poster
Aug 20, 2010
4
0
[
First, the newFrame variable is NOT an object. It's a CGRect, which is not an object.

Second, try rewriting the code without a temporary variable. See what it looks like. Is it clear what the code is doing?

Third, you've mistakenly called the array bracks, instead of bricks, and the temp variable Newframe instead of newFrame. Ordinarily I wouldn't bother correcting anyone's spelling or capitalization, but precision and clarity are crucial in programming, and Objective-C is case-sensitive.

Thanks for your corrections. But newFrame is not an object of class CGRect? I just want to clarify it. And where can I find all the info regarding CGRect like what is it, how is used, its method or syntax, etc? Any good Objective-C programming book you recommend? Because I found it is difficult to distinguish which is which in a code. For instance, in
Code:
UIImage *image = [ImageCache loadImage:brickTypes[count++ % 4]]
Is loadImage a class method of ImageCache? Will the whole thing return an object of class ImageCache? Then it is assigned to a pointer named image of class UIImage? Are these the correct names and types for all of them? The book I am reading doesn't explain what is what... Thanks for all your replies. :)
 

lloyddean

macrumors 65816
May 10, 2009
1,047
19
Des Moines, WA
NorthKyut,

Many of your questions can be self answered once you learn a little about navigating your code.

Locate 'CGRect' and while holding the Command key double-click it. You should be presented with a pop-up menu with the choice of 'strcut CGRect' or 'typedef CGRect'. Select the first one and you will be taken to the definition of CGRect where you'll find that it's a structure!

Next try holding down the Command key and double-click 'ImageCache' and you'll be taken to the implementation of the class since its code supplied within your project.

Command double-click 'loadImage' and you'll be taken to the implementation of 'ImageCache' where you'll discover it is a Class method.

Quick documentation of these things can usually be found by Option double-clicking them. While more complete documentation can be had with the use of Control double-clicking.
 

chown33

Moderator
Staff member
Aug 9, 2009
10,750
8,422
A sea of green
Apple has a lot of documents that cover fundamentals.

http://developer.apple.com/iphone/library/navigation/index.html#section=Topics&topic=General

I don't always find what I want using Apple's documentation search. I frequently use google with selected keywords and the site-qualifier.

For example, some keywords to use as search terms:

Getting Started - the entry point page to both overview and detail information.

Introduction or Fundamentals or Primer - when you want introductory docs or info about the fundamentals of a language, framework, or technology.

Guide - when you want the user guide or explanation.

Reference - when you want a specific class reference, as distinct from any associated Guide. For example, searching for NSString Reference finds the class reference, and on that page is a link to the String Programming Guide and the Property List Programming Guide.

iPhone - to get iOS-specific class references, guides, etc. as distinct from Mac versions. In general, most Foundation classes are identical, or nearly so. Most other frameworks can have varying overlap, from none to lots.

The "site qualifier" tells google to only return results from a particular website (hostname or domain). I usually use:
site:developer.apple.com
You enter that as another search term.

Examples of useful searches:
language guide iphone site:developer.apple.com
foundation reference iphone site:developer.apple.com
core graphics iphone framework site:developer.apple.com
The CG type-names all belong to the Core Graphics framework. So the last example above will show results for Core Graphics Framework Reference, which leads to a bunch of class docs, and a link to the CGGeometry reference, where CGRect and a lot of other types are documented. The search results also show a Getting Started document for all the iOS graphics technologies, and discusses why you'd use each one.


Cocoa Fundamentals Guide
http://developer.apple.com/iphone/l...ocoaFundamentals/WhatIsCocoa/WhatIsCocoa.html

Objective-C Programming Language
http://developer.apple.com/iphone/l.../ObjectiveC/Introduction/introObjectiveC.html
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.