An Introduction to Categories (Part 2 of 2)

Posted in IPhone App Programming on February 28th, 2011 by Admin

Using Categories to enhance models, and get rid of those pesky compiler warnings

Overview
When using Core Data, our model classes are always generated. What happens if we wanted to add a couple utility functions to one of these generated classes? Yep, they would be discarded the next time we auto-generated our model classes. As we discussed in our previous categories post (icodeblog.com), adding a category on one of these generated classes would enable us to add those utility functions in without them being erased when we generate the core data models.

For example:
Say we created a Model object called Person, and added two NSString attributes called firstName and lastName. If we had populated our Core Data base with several Person objects, and then went to retrieve them, we would have an unsorted array. What if we wanted them to be sorted based on their names? One of the ways to accomplish this could be to implement a function called compareByName: that will return an NSOrderedResult. We can use this utility function to sort that array of Person’s.

Given a Core Data generated class from a model object called Person, we are given a file and it’s header of the form

//Person.h
#import
@interface Person : NSManagedObject
{
}
 
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
 
@end
------------------------------------------------------------------------
//Person.m
#import "Person.h"
 
@implementation Person
 
@dynamic firstName
@dynamic lastName
 
@end

To add our category, we create an NSObject file of the name Person+Sorting.m, making sure that you check the create header file option.
As in the previous tutorial, change the files to actually be a category, and add in our new sorting function.

//Person+Sorting.h
@interface Person (Sorting)
 
- (NSOrderedResult)compareByName:(Person *)person2;
 
@end
----------------------------------------------------------------------------------------
//Person+Utility.m
@implementation Person (Sorting)
 
// Returns an NSComparisonResult caseInsensitiveCompare by lastName, and if that is the same, then by firstName
- (NSComparisonResult)compareByName:(Person *)person2 {
	NSComparisonResult result = [self.lastName caseInsensitiveCompare:person2.lastName];
	if (result == NSOrderedSame) {
		return [self.firstName caseInsensitiveCompare:person2.firstName];
	}
	return result;
}
@end

As you can see, I added in some code that first compare’s the Person objects based on their last name, and if those are equal compares them on their first names.

Now to use this category, all we have to do is add

#import "Person+Sorting.h"

to any file where we use Person, and we will be able to use that compareByName: function.

NSError *error = nil;
 
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
 
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
 
//Turn those unsorted results into a sorted array
NSArray *sortedPersons = [results sortedArrayUsingSelector:@selector(compareByName:)];
 
[request release];

There are of course other ways to get back sorted results from core data, but this is just one of the ways.

Getting rid of some compiler warnings
Another use of categories is to get rid of those pesky compiler warnings, when you call a function that is in the same file, however it is just lower down in the file.
The following code does not cause a compiler warning because the function we are calling comes first:

@implementation PersonViewController
 
- (void)loadPersonObjects {
	NSLog(@"function that comes before.");
}
 
- (void)viewDidLoad {
	[super viewDidLoad];
	[self loadPersonObjects];
}
@end

However if for some reason, like you want certain functions clumped together at one spot in a file, and you have viewDidLoad at the beginning, then something like the following would give a compiler warning.

@implementation PersonViewController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
	[super viewDidLoad];
	[self loadPersonObjects];
}
 
#pragma mark -
#pragma mark Load from Core Data Functions
//Other functions that load from core data also….
//.….
//.….
- (void)loadPersonObjects {
	NSLog(@"function that comes after.");
}
@end

To get rid of that compiler warning you can create a category on the current class in which you declare all the functions that are giving you warnings. You can do this at the beginning of the .m file after all the #imports, and before the actual @implementation of your class. The reason to do this is because you don’t want other classes calling these private classes, so you don’t want them in the header file, but you do want to get rid of the warnings. The following code snippet shows an example of fixing the warnings in the above class.

@implementation PersonViewController (__PRIVATE__)
- (void)loadPersonObjects;
@end
 
@implementation PersonViewController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
	[super viewDidLoad];
	[self loadPersonObjects];
}
 
#pragma mark -
#pragma mark Load from Core Data Functions
//Other functions that load from core data also….
//.….
//.….
- (void)loadPersonObjects {
	NSLog(@"function that comes after.");
}
@end


iPhone Programming Tutorials

Tags: , ,

iPad 2 is going to be pretty dull. Let’s call it 1.5

Posted in IPhone App Programming on February 28th, 2011 by Admin

Ben Harvell is a freelance writer and former editor of iCreate magazine. He writes for a wide range of international technology magazines and websites including Macworld and MacFormat. He has written several books on consumer technology and blogs at benharvell.com. Ben reviews apps and has also commissioned his own. He’s also rather obsessed with Twitter and suggests you follow him.

We’re a year on from the announcement of the first iPad and the rumour mill is in overdrive. Currently bouncing around are leaked specs, analyst predictions, mockups and tips for the next generation of iPad, expected this April. Trouble is, none of them are that interesting.

Let’s look at what the next iPad isn’t going to offer first:

1.There’s no way it’ll include a Light Peak connection. Maybe the upcoming MacBook Pros but definitely not the iPad. Apple doesn’t want the port messing up its design and it’s going to hold out on the dock connector as the only method of transfer for as long as possible.

2. There won’t be an equivalent to the iPhone 4′s Retina Display in the iPad 2. Not without a major price hike and a big drain on battery life, two essential selling points for the iPad.

The lack of anything interesting has caused the rumour sites to almost forget about the upcoming iPad and move on to the iPad 3 already. Allegedly coming in September alongside an iPod refresh, most are pinning their hopes on the extended period of time bringing about better deals and developments that could see major updates including a Retina Display.

It’s almost as if, should there be a Q1 2011 iPad at all, it’ll be more of an iPad 1.5 than a second generation device.

On the edge of dead-cert speculation for the iPad 1.5 we have word of a different screen, with current rumours pegging less reflective glass. We’ll also see front-facing a camera for sure. Apple wouldn’t give up the opportunity to put FaceTime on more units.

Then we’re left with staple Apple product upgrades. The iPad 1.5 will be thinner and faster. Yawn.

A faster graphics processor, maybe some more storage space and a thinner unit will be nice but it’s nothing groundbreaking, especially given the torrent of tablets that finally appeared at this year’s CES and Macworld shows. Apple likes to wow the crowd with its latest products and, if the above turns out to be accurate, most jaws will remain a long way from the floor.

The iPad is well ahead in the tablet market and, at this stage, Apple can afford to tweak rather than reinvent. I might be wrong, but this iPad 3 in September better be pretty special or 2011 could be the year Apple loses its lead.


Mobile Orchard

Tags: , , , , ,

Joseph Marello, Talent Manager at EA in Vancouver, Edmonton & Montreal meets Game Careers

Posted in Video Game Programming on February 27th, 2011 by Admin

Joseph Marello met with David Smith of Games Careers .Biz at the Montreal International Game Summit 2010. Joseph is the Manager of Talent Acquisitions at EA’s Studios in Vancouver, Edmonton and Montreal, Canada. Studios that he recruits for include EA Sports, Bioware and Visceral Games. He has 5 years experience on finding talent for Electonic Arts. His advice on getting a job at EA in Canada: “One thing you have to be is passionate, you have to do what you love to do and chase after that. If you check out our website there are opportunities up there all the time from junior right up to C-level. So have a look at our website and hopefully we will see you in the halls at EA.” See the full interview in the video that follows:

Share

Game Careers .BIZ – Video Games School, Jobs in Gaming.

Tags: , , , , , , , , ,

Apple media event next week, Happy Birthday Mr. Jobs, and more in this week’s news

Posted in IPhone App Programming on February 27th, 2011 by Admin

There is an Apple media event scheduled for March 2nd, what will they announce?

Endgadget revises their predictions for the iPad 2, which we should hear more about next week.

China may be getting the CDMA iPhone in June, complete with OTA activation.

Apples has decreased the minimum iAd buy from ,000,000 to 0,000. So if you have a half million just laying around…

Finally, Happy Birthday Steve Jobs.


Mobile Orchard

Tags: , , , , , , , , , , ,

Interesting tidbits for OpenGL programming on iPhone

Posted in IPhone App Programming on February 26th, 2011 by Admin

I have been following this blog for sometime and must say the author Wolfgang Engel is posting some of the best tips for game programmers on iPhone. A must bookmark for every iPhone programmer.

iPhoneDevelopmentBits

Tags: , , , ,

LINQ to SQL: XElement Not Being Updated in the Database

Posted in Programming Tips on February 26th, 2011 by Admin

If you are using LINQ to SQL to manage the interaction between your database and your application, you will notice that any columns you have defined as an XML SQL data type are represented using the XElement class in the generated classes. This makes working with XML data stored in a database very easy and convenient. But, today I ran into a problem while trying to update the XML stored in the database. My code followed the logic shown below.

// Get a report for the database
Report report = (from r in db.Reports
                 where r.Id == id
                 select r).First();

// The Report.Definition property is a representation of an XML column
// Get the first 'Group' element and add a new SubGroup child
XElement element = report.Definition.Elements("Group").First();
element.Add(new XElement("SubGroup", value));

// Commit the changes to the database
db.SubmitChanges();

The problem was that the changes made to the XML found in the Definition property were committed to the DataContext but not to the database.

After some research it appears that when SubmitChanges is called on the DataContext, it checks the entities it has retrieved to see if any changes were made. To do this, the DataContext must cache the original values it retrieved from the database. The problem with the code above is that when you access and change the report.Definition property directly, you are changing the value cached by the DataContext. Thus, when you call the SubmitChanges method and comparisons are made to the cached value, it appears nothing has changed as you edited the cached value. To solve this, do the following

// Get a report for the database
Report report = (from r in db.Reports
                 where r.Id == id
                 select r).First();

// The Report.Definition property is a representation of an XML column
// Get the first 'Group' element and add a new SubGroup child
XElement element = report.Definition.Elements("Group").First();
element.Add(new XElement("SubGroup", value));

// Force a reference inequality
report.Definition = new XElement(report.Definition);

// Commit the changes to the database
db.SubmitChanges();

Now when the DataContext checks to see if anything has changed, there will be a reference inequality between the original Report.Definition and the new XElement you assigned to Report.Definition. Unfortunately the LINQ to SQL classes don’t handle the XElement.Changed event and flag that something has changed.


stats.wordpress.com

Tags: , , , ,

Checking if Windows and/or your Program is 64-bit or 32-bit

Posted in Visual Basic on February 25th, 2011 by Admin

      A while back I made a simple post on using WMI to check if the operating system your program was running on was 32-bit or 64-bit. The main problem with that method is its not supported on Windows XP and doesn’t tell you what mode your application is running in. I made [...]
Visual Basic Source Code for FREE

Tags: , , , , ,

Checklist for iPhone developers and user interface designers

Posted in IPhone App Programming on February 25th, 2011 by Admin

APCmag has posted a list of things for iPhone developers and UI designers that will help in making a usable and beautiful iPhone app.

iPhoneDevelopmentBits

Tags: , , , , ,

The iPhone 4 truly is a completely new and innovative design

Posted in IPhone App Programming on February 24th, 2011 by Admin

Today i want to share my knowledge on technical gizmos iPhone 4 that makes you able to find the plans that best fits your needs .Here is a short Apple iPhone 4 review that gives you an idea to get the best gadget for your needs. The iPhone is more than just a phone. This handheld device does all of the normal things that a phone can do with some others besides. Additional extras include games, applications, spell checkers, the ability to surf the internet and the ability to listen to music and watch videos. The iPhone is able to be set up to the user’s individual requirements and it has been said that there is an iPhone application for everyone!

Apple iPhone 4:- This smart gadget comes powered by operating system i OS 4 with 1 G Hz Apple A4 processor that makes it outstanding among all. iPhone 4 is a 2G and 3G enabled handset, that not gives you highest speed of Internet accessibility with downloading and surfing but you can also make video conference to anyone without any extra charges.

You can get features of pocket PC that comes with a fantastic display of 3.5 inches LED-back lit IPS TFT, capacities touchscreen with display size of 640 x 960 pixels that gives it stunning and killing look, which supports 16M colors with an accelerometer sensor for auto-rotate, Scratch-resistant oleo phobic surface, Multi-touch input method, Three-axis gyro sensor and Proximity sensor for auto turn-off.. iPhone 4 comes with lucrative deals such as contract, Sim free and Pay as you go phones deals, which offered by almost major network carriers of UK market such as Vodafone, Three, Orange and many more. You can get so many exciting offers and gifts with iphone 4 Orange deals.

This smart phone has a fine camera of 5 mega pixel with a high resolution of 2592?1944 pixels, auto focus, LED flash featured with Geo-tagging and touch focus. It has an internal memory of 512 MB RAM with storage capacity of 16/32 GB, which can not expand. You can go through iPhone 4 review and get your dream gadget now.

iPhone Software Programming, iPhone apps Development, iPhone application development, iPhone programming, iPhone features

Tags: , , , ,

How to create a mini browser application for Windows Phone 7

Posted in Visual Basic on February 24th, 2011 by Admin

I have experienced a lot of fun writing Windows Phone 7 applications in Visual Basic. Web browser is one of the applications that is commonly used on phones these days. In this blog, I want to share some sample source code that will help you to create a mini browser application for Windows phone 7. I will now demonstrate how easy it is to develop a mini browser application for Windows Phone 7, using Visual Basic for Windows Phone Developer Tools.

The mini browser application can be created in 3 simple steps:

  1. Create a sample application and add controls and an event handler
  2. Build and debug the application
  3. Rebuild in release mode before publishing

Before you create a mini browser application, you need to install the following applications:

To create a mini browser application, follow the 3 simple steps mentioned earlier:

Step 1 – Create a sample application and add controls and an event handler

Create a sample application

  1. Create a new project and browse the “Select “Silverlight for Windows Phone” node.
  2. Select the “Windows Phone Application” template.
  3. Enter a name for the browser. 
  4. Click Ok. The MainPage.xaml page is displayed. 

Add controls

  1. Click the MY APPLICATION text. In the Properties window, change the text property to “MY FIRST APPLICATION”.
  2. Click the page name text. In the Properties window, change the text property to “Mini Browser”.
  3. To enable the application to work in both the portrait and landscape modes, add the support for both the orientations.
  4. Click the first line of the XAML code. In the Properties window, change the SupportedOrientation property to “PortraitOrLandscape”.
  5. From the Toolbox, drag and drop the Textbox control to the design surface.
  6. Click the Textbox. In the Properties window, change the text property to “http://www.xbox.com”.
  7. From the Toolbox, drag and drop the Button control to the design surface.
  8. Click the Button. In the Properties window, change the content property to “Go”.
  9. From the Toolbox, drag and drop the WebBrowser control to the design surface. Place it below the other two controls you added earlier.
  10. Add the following XAML code to set the height, width, and the alignment of the WebBrowser control. This allows the control to position itself correctly in both the portrait and landscape modes.

    <Grid x:Name=”ContentPanel” Grid.Row=”1″ Margin=”12,0,12,0″>

         <TextBox Height=”Auto” HorizontalAlignment=”Stretch” Margin=”0,0,120,0″ Name=”textBox1″ Text=”http://www.xbox.com” VerticalAlignment=”Top” />

         <Button Content=”Go” Height=”Auto” HorizontalAlignment=”Right”  Name=”button1″ VerticalAlignment=”Top” Width=”Auto” Click=”button1_Click” />

         <phone:WebBrowser HorizontalAlignment=”Stretch” Margin=”0,84,0,0″ Name=”webBrowser1″ VerticalAlignment=”Stretch” Height=”Auto” Width=”Auto” />

    </Grid>

Your application now looks like this:

 

Add an event handler

It is essential to add an event handler to the application because it helps to navigate to the entered URL.

To add an event handler, do the following:

  1. Double-click the Go button. The MainPage.xaml.vb page is displayed with the following code:

    Partial Public Class MainPage

        Inherits PhoneApplicationPage

        ‘ Constructor

        Public Sub New()

            InitializeComponent()

        End Sub

      

        Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles button1.Click

     

        End Sub

    End Class

  2. Replace the button1_Click event handler with the following code. This method will take the URL that is entered in the Textbox control and navigate to that page in the WebBrowser control.

    Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

            Dim site As String

            site = textBox1.Text

            webBrowser1.Navigate(New Uri(site, UriKind.Absolute))

    End Sub

Voila! Your mini browser application for Windows Phone 7 is ready! Now you just need to build and debug the application.

Step 2 – Building and debugging the application

  1. Select Debug > Build Solution. The project builds without any errors. If there are errors, check the earlier steps, correct any errors, and then build the application again.
  2. On the standard toolbar, set the deployment target of the application to “Windows Phone 7 Emulator”. 
  3. Debug the application by selecting Debug > Start Debugging. This opens the emulator window and launches the application. You can now test the application easily using the normal Visual Studio debugger and emulator controls.
  4. Click the Go button and verify that the browser window navigates to the given web site. 
  5. When you hover the cursor on the emulator, the edit panel of the emulator pops up. To test the application in the landscape mode, select the rotation control from the edit panel.

    The emulator rotates into the landscape mode and accordingly, the controls resize themselves to fit the screen. 
  6. Select Debug > Stop Debugging to stop debugging the application.

Step 3 – Rebuilding for the release before it can be published

  1. On the standard toolbar, change the configuration to Release. 
  2. Rebuild the application by selecting Build > Rebuild. The XAP file of the application is generated, which is the package you will have to submit to the marketplace in order to publish the application. You can also locate this XAP file in the Bin\Release folder.

 To submit your application to the market place, you can refer to upload your application walkthrough.

Summary

That’s it! You have now successfully created your first Windows Phone 7 Silverlight application, that too in just 3 simple steps! You can find the full source code for the Visual Basic Mini Browser application here. This application uses general Silverlight and Visual Basic features.


The Visual Basic Team

Tags: , , , , ,