Cocos2D help: How to setup and use SQLite database in cocos2D? - objective-c

I want to use SQLite database to store the scores of the games created with cocos2D framework. I use a singleton class controller called GameManager to control my application. To load the Scores I have a ScoreScene class which inherits CCScene and that class is called from GameManager, then when ScoreScene loads and from ScoreScene ScoreLayer class is called which inherits CCLayer class. I temporarily stored the score variable in GameManager and it is accessed from everywhere.
Now please help me and point out any weaknesses in my design and also help me in how I can implement SQLite database and store the score from GameManager class to the database.

The GameManager singleton seems to take the responsibility of managing common data and actions globally, right? Just be careful if there are multi-threading cases. I think your design is OK to use.
For SQLite part, you can refer to Apple official documentations if you want to use it via Core Data:
Core Data Programming Guide: Persistent Store Features
Core Data Programming Guide: Using Persistent Stores
Or you can use it via C interface directly. Some references:
http://klanguedoc.hubpages.com/hub/Tutorial-on-Creating-an-IOS-5-SQLite-Database-Application-IOS-5-SQLite
Use CoreData or SQLite on iPhone?

Related

Is Core Data the same thing as a Singleton in ios 7 development?

just started iOS 7 development. I'm building an app which stores a user profile. Certain data, like photos and reviews, need is related to multiple users.
From researching, I found that Core Data essentially provides this type of relational DB. But super n00bie question - is a Core Data the same as a Singleton? Which should I use for accessing user data across multiple viewControllers?
If I go the Core Data route, it seems that I'll have instantiate a Core Data object in every ViewController. Doesn't that seem excessive??
With Singletons, I won't have to do that, but I'll need to have proper thread management.
Sound right?
CoreData is an object model framework, and a singleton is a design pattern. This isn't even comparing apples to oranges, because apples and oranges are both fruits.
But your question makes it seem like you want to know how to access your data throughout your app. There are a few common patterns for this.
You typically use one or more instances of NSManagedObjectContext. You can pass this instance along to each view controller. Or you can have some singleton object which has a reference to the NSManagedObjectContext. This singleton is often the App Delegate, especially since the built in Xcode templates already come with a reference to your NSManagedObjectContext in the App Delegate.
it's not the same thing at all.
Core Data allows you to create subclass of NSMamagedObject which are object representing table in a sql data base stored on disk.
singleton are unique instance of any class (usually if not never an NSManagedObject).
read on wikipedia about singleton it's a good article.
both have nothing to do with iOS7

Objective-C Alternative to using ApplicationDelegate or singleton to pass data

I'm working on an exiting iOS app (called Mazin in the App store, if anyone is interested) and I'm trying to rework the code to avoid using the Application Delegate or a singleton for sharing information/methods. In particular I have the following to share across certain views and controllers:
CoreData objects like NSManagedObjectConttext and related custom methods for interacting with the data
State properties used in several places like currentMazeType, gameMode, and soundIsMuted along with a few widely used utility methods particular to the game
Views and methods used to display information used commonly throughout the app (e.g., an ActivityIndicator and methods to show/hide it on a given view)
In general, several views and ViewControllers need access to various subsets of this information and I need a mechanism to share the information and methods "globally" across these objects. Some of this sharing is for convenience (e.g., every time I want to display a basic activity indicator, I just call a common "startActivityIndicator" method) but some are required (e.g., changing gameMode changes it "globally" and several views/controllers need to access the common mode info).
What sort of patterns would work best for this requirement? I have my own solution in mind, and I'll post it below for your consideration/comments.
Thanks!
Solution I am considering:
I plan to create a few "utility" classes (e.g. GameDataUtil, AppStateUtil, GadgetsUtil) that each encapsulate a proper subset of the "global" information and/or methods. Each View or ViewController that needs to access the common info/methods in a utility will have an appropriate property of that given type (e.g., a view that can make a sound needs access to the AppStateUtil so it can determine if sounds are currently muted).
The ApplicationDelegate will be the only class that generates single instances of the "utility" classes and will pass those instances to the appropriate objects that get loaded from its Nib (in applicationDidFinishLaunching). Those views/controllers will have to pass all necessary information to any of their members that they may load programmatically (which could get hairy--class A may need a GagetsUtil in order to pass it to an instance of class B even though class A never uses the utility directly).
This is sort of like injecting dependencies from the application delegate down (since I don't have the utility of an Dependency Injection Container).
Now, I have thought about creating an uber-utility (e.g., ConfigUtil) that would hold one property for each of the other utilities. The AppDelegate would create a single instance of the uber-utility (setting it up with instances of the other utilities it creates). The AppDelegate would pass the uber-utility instance to anyone who needs access to any of the basic utilities. Each basic utility would still encapsulate a sub-set of the common data/methods, but by putting one of each into an uber-utility and passing it around, I don't have to keep up with which utility is needed by which class (not only for its own use but also to pass to any of its member objects).
NSNotification would be a step away from that model, and is typically easy to implement.
If many things know of and refer to mutable global data right now... it will take time to undo that.
Update
I remembered that I had written a more detailed response to a similar scenario here at SO.

Need help with application design (MVC, classes etc.)

I'm pretty new to object oriented programming (do have scripting knowledge in PHP and Posix shell programming) and I'm working on a beer recipe application. I've already started the project, but I guess the design is not that good from a MVC point of view. I hope you will help me get the design right. Here are a couple of things to know about the application.
The application needs to be a Document Based Application (open/save recipes in Beer XML). The main window has several textfields to set information like: name, beertype, volume etc. Then there are a couple of tableviews with arrays for: malts, hops and spices, each having their own sheet for adding values.
How should I make my classes? Like this?
NSDocument class (with the open/save XML code)
(3x) NSWindowController (for each sheet: malts, hops, spices)
(3x) NSArrayController (for each tableview: malts, hops, spices)
Should the arrays, managed by the NSArrayController objects, be separate classes (in a MVC perspective (as Model)) or should they be incorporated into their NSArrayController class?
I would start by brushing up on a couple of Apple provided docs:Object-Oriented Programming with Objective-C and Cocoa Fundamentals Guide.
I would also look at using Core Data. With relatively little implementation you have a very powerful data structure (the M in MVC) that is easy to implement with your view and view controllers (the V & C):
Core Data Programming Guide
I highly recommend reading these. They are not bad reads and you gain a TON of knowledge. Apple docs are really the best.
Good luck.
Assuming that these are your requirements,
Editor application that uses xml (beerxml) as it datasource.
Viewer that shows the available data (in a tabular format or as sheets)
User can add/remove/edit entries in each xml
There exists a relationships between the xmls (datasources) (unsure...)
Before applying any design pattern, you should start applying the basic OOP concepts to identify and create classes (state and behavior) and define the relationship between the classes.
For example, receipes.xml is used to denote the recipes used to manufacture a product. To design a class for this go through the xml. You can identify the following data classes (objects i.e. instances of classes represent a real world entity, while the class is more like a template/blue print for the object):
Recipe (main class)
Hop
Fermentable
Yeast
Water
Style
Equipment
Mash
MashStep
and so on.
Once you have identified the classes that form your data model (information repository), identify the properties and behavior of each class. For example, the Yeast class would contain the properties, Name, Version, and so on. Do not worry about the type of the property (string, integer, etc.).
To identify the controllers, view the application from the point of view of the user. What are the use cases (what does the user do with the application? Edit? Add? etc.). These use cases will inadvertently require processing information in a particular flow (sequence). The information is available in your model classes. The controller will invoke operations on the model classes and determine the interaction between them.
For example, suppose there is a use case that the use needs to add a new yeast to the system. Then the controller would create a new instance of the Yeast class and populate it with values supplied by the user (after performing some sort of validation). The created yeast would then be added to the ListOfAvailableYeasts and made available to other classes.
The view is (as the name suggests), a user interface to your data. In MVC, the view is usually updated by an observer that monitors the model for changes and updates the UI accordingly (there are several variation to MVC pattern).
The main point here is that you should first focus on object orientation design first rather than jumping directly into the design patterns.
If you need some guidelines on how to create classes from the xml, then take a look at the xsd.exe tool. You can generate the xsd (xml schema) from an xml and then use this xsd to generate a class hierarchy for the xml (I suggest you start with recipes.xml). You can modify the generated classes to your requirement.
The generated classes would look something like this,
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class RECIPESRECIPE {
private string nAMEField;
private string vERSIONField;
private string tYPEField;
private string bREWERField;
private string aSST_BREWERField;
private string bATCH_SIZEField;
...
}
Hope that this is sufficient to get you started.

How to access a class from another class?

I’m fairly new to OO. If I have two classes A and B that need to exchange data, or call each other’s methods, I need to be able to access an instance of class B from class A. Should I maintain the address of the instance object in a global variable? Should I appoint a (singleton) master class, and make (pointers to) instances of A and B properties of the master class? (AppDelegate comes to mind.)
Is there a straightforward by-the-book way to implement this? Somehow I‘m missing some "best practice" here. I’ve looked through Apple's examples, but didn't find an answer.
EDIT: Since I'm fairly new to MVC design patterns, my question is essentially "Who creates who"?
We're talking about an Audio Player here. 1. When the user selects a song, the UI displays its waveform by creating a viewController which creates the appropriate view. 2. When the user hits play, the UI displays a timeline while the song is playing by overlaying a new view over the waveform. Now, the latter view needs some info from the waveform display viewController. Right now, I'm storing a pointer to the viewController in an instance variable of my appDelegate. This works, but feels extremely strange.
Should I outsource the info that is needed by both classes to some third entity that every class can access easily?
Classes aren't simply departments of code. They are templates for the creation of objects, which you should think of as actors in your program, doing things within their areas of responsibility (which you define—you decide what each object does) and interacting with each other.
While you can handle a class as you would an object, classes generally do not talk to each other. Most of the time, you will create and use instances of the classes—which is what we normally mean by “objects”—and have those talking to each other. One object sends another a message, telling the receiver to do something or changing one of the receiver's properties. These messages are the interactions between your program's objects.
Those weird expressions in the square brackets are message expressions. Nearly everything you'll do with a class or object will involve one or more messages. You can send messages to classes the same as to objects, and classes can send messages just as objects can.
In Cocoa and Cocoa Touch, you typically have model objects, view objects, controller objects, data objects (such as NSString, NS/UIImage, and NSURL), and helper objects (such as NSFileManager). The classes you'll write for your application will mainly be model, view, and controller objects (MVC). The model represents (models) what the user will see themselves manipulating; the view displays the model to the user; the controller implements logic and makes sure the model gets saved to and loaded from persistent storage.
For more information, see Object-Oriented Programming in Objective-C and the Cocoa Fundamentals Guide.
Since I'm fairly new to MVC design patterns, my question is essentially "Who creates who"?
Controllers create and load the model, and load the views, and pass the model to the view for display. Certain controllers may also create other controllers.
It's good to keep a straightforward tree-like graph of ownership from a single root of your program—typically the application object—down through controllers to leaf objects in the models and views. If two objects own each other, that's a problem. If an object is not owned by anything outside of its own class (a singleton), that's usually a problem as well—a sign you need to think some more about where that code belongs. (Helper objects are the main exception; most of those are singletons. Again, see NSFileManager for an example. But they are few and far between.)
Further situation analysis require more information. At first place you should more specify the relation between classes and what exactly do you mean by exchanging data.
Singletons should be generally avoided. If you want to exchange information it is usually sufficient to provide for example instance of the class A to the instance of the class B by some method or constructor. The instance of B is then capable of calling public methods (and accessing public properties) of the instance of A.
A little bit of "best practices" can be learn by searching up "Design Patterns".
You should decide if one class can be an object of another class (encapsulation), or if one class can inherit from the other class (inheritance). If neither of these is an option, then maybe you could make one class (or some of its members) static?
Thanks for your contributions. Additionally, I found information on this page very useful. It lays out MCV considerations for cocoa in a hands-on way and practical language.

iOS: Multiple views accessing the same data - how to access?

I'm a Java Developer new to iOS and objective c development.
I need to build an iOS application where multiple views (e.g. a ListView and a MapView) access the same data (e.g. stored in an NSArray).
Currently, I do alloc and init a DataManager class that loads the data (loading it from a plist, later it should be requested from the web) in the app delegate.
How do I access this data from the views? Should the DataManager be a singleton? Is there a better/more elegant/more "obj-c 2.0" solution?
Thanks!
Use the MVC architecture. Your data is a model object, which can be passed to the various controllers that use the data to populate the views. In Cocoa Touch, the views are the UIView subclasses that you typically create in XIB files. The controllers usually start with UIViewController instances that manage the views, but include things like table view delegates and data sources. The models are the objects you create to represent the data - your DataManager class.
There are plenty of frameworks in the Java world that use the MVC pattern, so you may already be used to dividing classes up this way if you've come across e.g. Spring MVC, or Eclipse RCP.