
registerType('appdoo.iOSGenerator', (function () { function iOSAppGenerator() {} var __super = setSupertypeFromDomain(iOSAppGenerator, 'BasicObject', 'Core');

iOSAppGenerator.prototype.initFromData = function iOSAppGenerator_initFromData(data) {

		this.storyboardTransformer = createComponentFromDomain(
			'AppleStoryboardTransformer', 'appdoo.iOSGenerator', this.context, {
				productGenerator: this
			});

		this.pbxFileGenerator = createComponentFromDomain(
			'PbxFileGenerator', 'appdoo.iOSGenerator', this.context, {
				productGenerator: this
			});
		
		this.images = [];
		this.imageResources = [];
		this.projectName = data.projectName;
		this.hidesStatusBarOnLaunch = 0;
        this.statusBarStyle = 0;
		this.dataSources = [];
		this.resources = [];
		this.plugins = {};

		this.codeIDs = [];
		this.viewControllerCodeIDs = {};
		this.viewControllerByCodeIDs = {};
		this.dataSourceCodeIDs = {};
		this.propertyNameForProjectID = {};
		this.cellForViewController = {};
		this.globalOutletNames = [];

		
		
		this.viewControllers = {};
		this.tableViewCells = {};
		this.collectionViewCells = {};
		
		this.pluginObjects = [];
		this.includeHeaders = {};
		this.includeHeadersForThing = {};
		this.classNamesWithoutHeader = {};
		this.outletHeaders = {};
		this.inlineObjectsForOriginalSceneID = {};
		this.inlineObjectsForCellViewCID = {};
		this.globalInlineObjects = [];
		this.parentViewControllerClassForEmbeddedScene = {};
		this.parentViewControllerCIDForEmbeddedScene = {};
		this.embeddedViewControllersInViewControllerCID = {};
		this.propertyForOriginalID = {};
		this.connectionsInCode = {};

		this.overwritesModalInterfaceOrientations = true;
		
		this.payload = {
			projectName: data.projectName,
			files: [],
			referencedFiles: [],
			buildFileItems: {},
			fileReferenceItems: {},
			projectGroupItems: [],
			supportingFilesGroupItems: [],
			frameworksGroupItems: [],
			otherGroups: {},
			pluginGroups: {},
			otherGroupsInRootList: [],
			sourcesBuildPhaseItems: [],
			resourcesBuildPhaseItems: [],
			frameworksBuildPhaseItems: [],
			variantGroupItems: {},
			librarySearchPaths: [],
		};
		
		this.licencedPlugins = [];
				
		return this;};
	
	

	Object.defineProperty(iOSAppGenerator.prototype, "outletForOriginalID", {
		get: function () {
			return this.propertyForOriginalID;
		}});
	
	Object.defineProperty(iOSAppGenerator.prototype, "outletNameForProjectID", {
		get: function () {
			return this.propertyNameForProjectID;
		}});
	

	

iOSAppGenerator.prototype.generateFromData = function iOSAppGenerator_generateFromData(originalData) {

		var dataCopy = JSON.parse(JSON.stringify(originalData)),
			result = { generatedFiles: {} };
		this.originalData = dataCopy;

		this.dataSources = this.filterDataSourcesFromData(dataCopy);

		if (Array.isArray(originalData.fileReferences)) originalData.fileReferences.every(function (ref) {
			this.resources.push(ref);return true; }, this);
		

		this.targetDeviceIsIPad = (originalData.metadata.deviceProfile.indexOf('iPad') === 0);
		this.targetIsIOSUniversal = (originalData.metadata.targetedDeviceFamily == 'iOS-Universal');

		this._generateInfoPlistFile(result.generatedFiles, dataCopy);
		this._generateStoryboardFile(dataCopy, result.generatedFiles);
		
		this.isTransformingGlobalObjects = true;
		this.prepareGlobalObjects(dataCopy.objects);
		this._generateGlobalObjectsFile(dataCopy, result.generatedFiles);
		this.prepareGlobalObjects(this.globalInlineObjects);
		this._generateAppDelegate(dataCopy, result.generatedFiles);
		this.isTransformingGlobalObjects = false;
		
		for (var key in this.viewControllers) {
			this.currentViewController = this.viewControllers[key];
			this._generateViewControllerFiles(key, result.generatedFiles);
		}
		
		this.currentViewController = null;

		for (var key in this.tableViewCells) {
			this.currentCell = this.tableViewCells[key];
			this._generateTableViewCellFiles(key, result.generatedFiles);
		}

		for (var key in this.collectionViewCells) {
			this.currentCell = this.collectionViewCells[key];
			this._generateCollectionViewCellFiles(key, result.generatedFiles);
		}

		this.currentCell = null;
		
		this.demandPluginWithIdentifier('info.appdoo-mac.SimpleScrollView');
		this.demandPluginWithIdentifier('info.appdoo-mac.LayoutResolver');
		this.demandPluginWithIdentifier('info.appdoo-mac.UIAlertControllerAdditions');

		if (Array.isArray(this.context.projectContext.fileReferences)) this.context.projectContext.fileReferences.every(function (ref) {
			if (ref.isFont) {
				this.demandPluginWithIdentifier('info.appdoo-mac.UIViewFontNameAndSizeProperty');
				return false;
			}return true; }, this);
		

		this._generatePbxFile(result.generatedFiles, result.referencedFiles);
		
		result.imageNames = this.imageResources;
		result.dataSources = this.dataSources;
		result.resources = this.resources;
		result.plugins = this.plugins;

		if (this.imageRefIsValid(originalData.metadata.iconImage)) {
			result.appIconImageID = this.handleInlineImage(originalData.metadata.iconImage, true, '', true);
		}

		result.deviceType = _context.projectContext.simulatedDeviceType;
		if(this.targetIsIOSUniversal) {
			result.deviceType = "iOS-Universal"
		}
		result.launchImages = originalData.metadata.launchImages;
		
		this.payload.files = this.payload.files.concat(Object.keys(result.generatedFiles));
		
		if (this.licencedPlugins.length) {
			result.generatedFiles['Licences.html'] = this.generateLicencesFile();
			this.payload.files.push('Licences.html');
		}
		
		result.generatedFiles[this.projectName+'/appdooPayload'] = this.generatePayloadFile();
		
		var serialized = JSON.stringify(result);
		return serialized;
		};
	
	
iOSAppGenerator.prototype.generateLicencesFile = function iOSAppGenerator__generateLicencesFile() {
		var str = '<html><body><h1>Licences</h1>';

		if (Array.isArray(this.licencedPlugins)) this.licencedPlugins.every(function (pluginIdentifier) {
			var plugin = window.availablePlugins[pluginIdentifier];
			if (!plugin.licenceFile) return true;
			
			var licenceFilePath = plugin.path + '/Product/' + plugin.licenceFile;

			var licence = this.context.nativeProxy.sendMessage('stringFromFile', licenceFilePath);
			str += '<b>'+plugin.licenceProductNames+'</b>\n';
			str += '<pre style="white-space:pre-wrap">' + licence + '</pre>\n\n';return true; }, this);
		
		
		
		str += '</pre></body></html>';
		
		return str;};
	
	
	Object.defineProperty(iOSAppGenerator.prototype, "keepPluginReferences", {
		get: function () { return this.context.isDebugging; }});
	

iOSAppGenerator.prototype.handleInlineImage = function iOSAppGenerator_handleInlineImage(imageRef, skipRemoveAt2x, contentMode, returnID) {
		if (contentMode === undefined) contentMode = 'center';
		if (!imageRef || !imageRef.imageID) return '';
		if (imageRef.fileReferenceID) {
			var ref = _context.projectContext.fileReferenceWithID(imageRef.fileReferenceID);
			if (ref) {
				if (returnID) return ref.resourceID;
				if (!skipRemoveAt2x) return ref.name.replace('@2x','');
				return ref.name;
			}
		}
		else {
			if (returnID) return imageRef.imageID;
			var imageName = imageRef.imageID;
			if (!skipRemoveAt2x) imageName = imageName.replace('@2x','');
			this.registerImage(imageRef.imageID, 'center');
			return imageName;
		}
		return '';};
	
		
iOSAppGenerator.prototype.generatePayloadFile = function iOSAppGenerator__generatePayloadFile() {
		this.payload.files.push(this.projectName+'/appdooPayload');
		return JSON.stringify(this.payload, null, '	');};
	
	
iOSAppGenerator.prototype.filterDataSourcesFromData = function iOSAppGenerator__filterDataSourcesFromData(data) {
	
		var dataSources = [];
		
		if (Array.isArray(data.objects)) data.objects.every(function (instance) {
			if (instance.$domain === 'appdoo.DataSources') {
			
				var codeID = this.createCodeID(instance.name || 'DataSource', true);
				this.dataSourceCodeIDs[instance.$id] = codeID;
				
				var copy = clone(instance);
				copy.codeID = codeID;
				dataSources.push(copy);

			}return true; }, this);
		
		
		return dataSources;
	};
	
	
iOSAppGenerator.prototype.createCodeID = function iOSAppGenerator_createCodeID(str, cap) {
	
		var id = this.generateCodeCompliantID(str, cap),
			_id = id,
			num = 1;

		while (this.codeIDs.indexOf(_id) !== -1)
		{
			_id = id+num;
			num++;
		}
		
		this.codeIDs.push(_id);
		return _id;};
	

	function isNumber(x) {
		return typeof x === 'number';
	}
	
	

iOSAppGenerator.prototype.generateCodeCompliantID = function iOSAppGenerator__generateCodeCompliantID(id, cap) {
	
		var capitalize = function (str) {
			return str.charAt(0).toUpperCase() + str.slice(1);
		};
		
		var str = id;
	
		
		str = str.replace(/ä/g, 'ae');
		str = str.replace(/ö/g, 'oe');
		str = str.replace(/ü/g, 'ue');
		str = str.replace(/ß/g, 'ss');

		
		str = str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
			return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
		}).replace(/\s+/g, '');
		
		
		if (isNumber(str[0])) {
			var numberNames = {
				'0':'zero',
				'1':'one',
				'2':'two',
				'3':'three',
				'4':'four',
				'5':'five',
				'6':'six',
				'7':'seven',
				'8':'eight',
				'9':'nine',
			};
			str = numberNames[str[0]] + capitalize(str.slice(1));
		}

		
		
		var filtered = '';
	    for (i = 0, c = str.length; i < c; i++) {
	    	var cc = str.charCodeAt(i);
	    	if (
	    		(cc >= 48 && cc <= 57) 
	    	 || (cc >= 65 && cc <= 90) 
	    	 || (cc >= 97 && cc <= 122) 
	    	 || cc === 95 
	    	 )
	    	 	filtered += str[i];
	    }

		if (cap === true)
			filtered = capitalize(filtered);
		
		return filtered;
};
	
	
iOSAppGenerator.prototype.codeIDForViewControllerID = function iOSAppGenerator_codeIDForViewControllerID(id) {
		return this.viewControllerCodeIDs[id];};
	


	

iOSAppGenerator.prototype.registerViewController = function iOSAppGenerator_registerViewController(originalData, sourceSceneData) {
	
		var originalID = originalData.$id;
	
		var codeID = this.createCodeID('ViewController '+originalData.title, true);

		this.viewControllers[codeID] = {
			originalData: originalData,
			outlets: {},
			outletByOriginalID: {},
			otherProperties: {},
			dataSources: [],
			sourceSceneData: sourceSceneData
		};
		
		this.viewControllerCodeIDs[originalID] = codeID;
		this.viewControllerByCodeIDs[codeID] = originalID;
		return codeID;};
	
	
iOSAppGenerator.prototype.addOtherProperty = function iOSAppGenerator_addOtherProperty(originalData, propertyType) {
	
		var originalID = originalData.$id;
		if (!propertyType) {
			var cocoaType = this.cocoaTypeForData(originalData),
				cocoaCustomType = this.cocoaCustomTypeForData(originalData);
			propertyType = cocoaCustomType || cocoaType;
		}
	
		var codeID = this.viewControllerCodeIDs[this.storyboardTransformer.currentViewControllerId];
		var currentViewController = this.viewControllers[codeID];

		if (currentViewController) {

			var name = this.generateOutletName({$type:propertyType});
			
			var prop = {
				name: name,
				className: propertyType,
				customClass: propertyType,
				originalData: originalData,
				classId: this.storyboardTransformer.currentViewControllerClassId,
				type: propertyType
			};
			
			currentViewController.otherProperties[name] = prop;
			this.propertyForOriginalID[originalID] = prop;
			this.propertyNameForProjectID[originalID] = name;
			
			return name;
		}};
	

iOSAppGenerator.prototype.registerOutlet = function iOSAppGenerator_registerOutlet(name, className, customClass, bindings, classId, originalData) {
	
		var outlet = {
			name: name,
			className: className,
			customClass: customClass,
			bindings: bindings,
			originalData: originalData,
			classId: classId
		};
		
		this.outletForOriginalID[originalData.$id] = outlet;
	
		if (this.viewControllers[classId] !== undefined) {
			this.viewControllers[classId].outlets[name] = outlet;
			this.viewControllers[classId].outletByOriginalID[originalData.$id] = outlet;
		}
		else if (this.tableViewCells[classId] !== undefined) {
			this.tableViewCells[classId].outlets[name] = outlet;
			this.tableViewCells[classId].outletByOriginalID[originalData.$id] = outlet;
		}
		else if (this.collectionViewCells[classId] !== undefined) {
			this.collectionViewCells[classId].outlets[name] = outlet;
			this.collectionViewCells[classId].outletByOriginalID[originalData.$id] = outlet;
		}
		else {
			 console.warn('registerOutlet() failed - no such class registered: ',
			classId, outlet, this.viewControllers);
			 console.trace();
			return;
		}
		};
	
	
iOSAppGenerator.prototype.registerTableCellClass = function iOSAppGenerator_registerTableCellClass(cellIdentifier, tableViewData, originalData, vcCodeID) {

		this.tableViewCells[cellIdentifier] = { outlets: {}, outletByOriginalID: {}, tableViewData: tableViewData, originalData: originalData };
		
		this.cellForViewController[vcCodeID] = cellIdentifier;

		return cellIdentifier;};
	
	
iOSAppGenerator.prototype.registerCollectionCellClass = function iOSAppGenerator_registerCollectionCellClass(cellIdentifier, collectionViewData, originalData, vcCodeID) {

		this.collectionViewCells[cellIdentifier] = { outlets: {}, outletByOriginalID: {}, collectionViewData: collectionViewData, originalData: originalData };

		this.cellForViewController[vcCodeID] = cellIdentifier;

		return cellIdentifier;};
	
	
	var skipValidation = 0;

iOSAppGenerator.prototype.registerImage = function iOSAppGenerator_registerImage(imageName, contentMode) {

		
		if (!this.registerImageHistory) this.registerImageHistory = {};
		if (this.registerImageHistory[imageName+contentMode]) return;
		this.registerImageHistory[imageName+contentMode] = true;
	
		if (!skipValidation && !this.imageIsValid(imageName)) {
			 console.warn('Invalid image detected, skipping.', imageName);
			return;
		}
	
		var hasRetinaVariant = skipValidation?false:!!this.context.nativeProxy.sendMessage('pathForRetinaImageWithID',imageName);
	
		
		if (imageName.indexOf('.') === -1) imageName += '.png';
		var pathExtension = getPathExtension(imageName);

		if (hasRetinaVariant || contentMode === 'center') {
			
			var name2 = imageName.substr(0, imageName.length-pathExtension.length-1)+'@2x.'+pathExtension;
			
			
			
			name2 = name2.replace(/@2x@2x/, '@2x');
			
			if (this.images.indexOf(name2) === -1)
				this.images.push(name2);
		}

		if (contentMode !== 'center') {
			if (this.images.indexOf(imageName) === -1)
				this.images.push(imageName);
		}
		

		this.imageResources.push({
			contentType: 'image/'+pathExtension,
			name: imageName,
			hasRetinaVariant: hasRetinaVariant,
			contentMode: contentMode
		});};
	
	
	
iOSAppGenerator.prototype.demandPluginWithIdentifier = function iOSAppGenerator_demandPluginWithIdentifier(pluginIdentifier, viewController, cell) {
		return this.registerObjectWithPluginIdentifier(null, pluginIdentifier, viewController, cell);};
	
	

iOSAppGenerator.prototype.registerPluginObject = function iOSAppGenerator_registerPluginObject(data, viewController, cell, other) {
	
		var pluginIdentifier = this.pluginIdentifierForData(data);
		
		return this.registerObjectWithPluginIdentifier(data, pluginIdentifier, viewController, cell, other);
		};
	
	
	
iOSAppGenerator.prototype.registerObjectWithPluginIdentifier = function iOSAppGenerator_registerObjectWithPluginIdentifier(data, pluginIdentifier, viewController, cell, other) {
	
		var plugin = window.availablePlugins[pluginIdentifier];
			alertd('meep', 'pluginIdentifier', pluginIdentifier, plugin);
		
		if (!plugin) {
			 console.error('Missing plugin!', pluginIdentifier, window.availablePlugins);
			return;
		}
		
		if (data) {
			this.pluginObjects.push({
				data: data,
				viewController: viewController,
				cell: cell,
				pluginIdentifier: pluginIdentifier
			});
		}


		if (!this.plugins.hasOwnProperty(pluginIdentifier))
			this.plugins[pluginIdentifier] = plugin.path;
		
		if (plugin.includeHeader) {

			alertd('meep', 'plugin.includeHeader', plugin.includeHeader);

			var path = plugin.includeHeader;
			if (this.isTransformingAppDelegate) {
				this.addIncludeHeaderForThingWithOriginalID(path, 'AppDelegateImplementation');
			}
			if (this.isTransformingGlobalObjects) {
				this.addIncludeHeaderForThingWithOriginalID(path, 'AppDelegate');
			}
			else {
				this.addIncludeHeaderForThing(path, cell || viewController || other);
			}
		
		}

		if (plugin.requiresPlugins) {
			if (Array.isArray(plugin.requiresPlugins)) plugin.requiresPlugins.every(function (p) {
				this.demandPluginWithIdentifier(p);return true; }, this);
			
		}
		};
	

iOSAppGenerator.prototype.registerClassWithoutHeader = function iOSAppGenerator_registerClassWithoutHeader(className, viewController) {
		if (!viewController) return;
		var id = viewController.$id;
		if (!this.classNamesWithoutHeader[id]) this.classNamesWithoutHeader[id] = {};
		this.classNamesWithoutHeader[id][className] = true;};
	

iOSAppGenerator.prototype.classNamesWithoutHeaderForVCData = function iOSAppGenerator__classNamesWithoutHeaderForVCData(vcData) {
		var originalViewControllerID = vcData.originalData.$id;
		return this.classNamesWithoutHeader[originalViewControllerID];};
	
	
iOSAppGenerator.prototype.getAppearanceDataForViewController = function iOSAppGenerator_getAppearanceDataForViewController(viewController) {

		var globalSettings = getType('appdoo.iOS.UIViewController').prototype.globalSettings,
				properties = ['navigationBarType','navigationBarTintColor','navigationBarBackgroundImageID','navigationBarTitleLabelFontName','navigationBarTitleLabelFontSize','navigationBarTitleLabelOffset'],
				derivedData = {};
			
			if (viewController.usesGlobalNavigationBarAppearance) {
				if (Array.isArray(properties)) properties.every(function (prop) {
					derivedData[prop] = globalSettings[prop];return true; }, this);
				
			}
			else {
				if (Array.isArray(properties)) properties.every(function (prop) {
					derivedData[prop] = viewController[prop];return true; }, this);
				
			}
			
		return derivedData;};
	


	

iOSAppGenerator.prototype._generateStoryboardFile = function iOSAppGenerator___generateStoryboardFile(data, result) {
	
		result[this.projectName+'/Main.storyboard'] =
			this.storyboardTransformer.transformData(data);
	};
	
	
iOSAppGenerator.prototype._generateGlobalObjectsFile = function iOSAppGenerator___generateGlobalObjectsFile(data, result) {

		var xibGenerator = createComponentFromDomain("XIBGenerator", "appdoo.iOSGenerator", this.context, {
			productGenerator: this})
		;

		result[this.projectName+'/GlobalObjects.xib'] =
			xibGenerator.generateXIBFromObjects(data.objects);
};
	


	

iOSAppGenerator.prototype._generateViewControllerFiles = function iOSAppGenerator___generateViewControllerFiles(classId, result) {

		var id = this.viewControllerByCodeIDs[classId];
		var viewControllerData = this.viewControllers[classId],
			templateName = 'UIViewController';

		result[this.projectName+'/'+classId+'.h'] =
			this._generateViewControllerHeaderFile(
				classId, viewControllerData, templateName);

		result[this.projectName+'/'+classId+'.m'] =
			this._generateViewControllerImplementationFile(
				classId, viewControllerData, templateName);
};
	

	function is_empty(obj) {
	
		if (Array.isArray(obj) && obj.length > 0)
			return false;
	
		for (var key in obj) {
			if (obj[key] !== undefined)
				return false;
		}
	
		return true;
	}
	
	function viewControllerHasCollectionView(vcData) {
		return !!(vcData.outlets.collectionView);
	}
	
iOSAppGenerator.prototype.includeHeadersForVCData = function iOSAppGenerator__includeHeadersForVCData(vcData, isImplementationFile) {
		var originalViewControllerID = vcData.originalData.$id;
		if (!isImplementationFile)
			return this.includeHeadersForThing[originalViewControllerID];
		else {
			var result = {};
			for (var key in this.includeHeaders) { result[key] = true; }
			for (var key in this.includeHeadersForThing[originalViewControllerID+'Implementation']) { result[key] = true; }
			return result;
		}};
	

iOSAppGenerator.prototype.includeHeadersForCellData = function iOSAppGenerator__includeHeadersForCellData(cellData) {
		var originalCellID = cellData.originalData.$id;
		return this.includeHeadersForThing[originalCellID];};
	

iOSAppGenerator.prototype.includeHeadersForAppDelegate = function iOSAppGenerator__includeHeadersForAppDelegate(isImplementationFile) {
		if (!isImplementationFile)
			return this.includeHeadersForThing['AppDelegate'];
		else {
			var result = {};
			for (var key in this.includeHeaders) { result[key] = true; }
			for (var key in this.includeHeadersForThing['AppDelegateImplementation']) { result[key] = true; }
			return result;
		}};
	
	
iOSAppGenerator.prototype.addIncludeHeaderForThing = function iOSAppGenerator__addIncludeHeaderForThing(headerPath, originalData) {
		if (originalData)
			this.addIncludeHeaderForThingWithOriginalID(headerPath, originalData.$id);
		this.includeHeaders[headerPath] = true;};
	

iOSAppGenerator.prototype.addIncludeHeaderForThingWithOriginalID = function iOSAppGenerator_addIncludeHeaderForThingWithOriginalID(headerPath, id) {

		if (!this.includeHeadersForThing[id])
			this.includeHeadersForThing[id] = {};

		this.includeHeadersForThing[id][headerPath] = true;};
	

iOSAppGenerator.prototype._generateViewControllerHeaderFile = function iOSAppGenerator___generateViewControllerHeaderFile(classId, viewControllerData, templateName) {
	
		var result = this._getTemplate(templateName, 'header');
		if (!result) {
			 console.error('Template not found!');
			return '';
		}
		result = result.replace(/__UIVIEWCONTROLLER_CLASS__/g, classId);
		result = result.replace(/__UIVIEWCONTROLLER_BASE_CLASS__/g, viewControllerData.originalData.$type||viewControllerData.originalData.constructor.name);
		result = result.replace(/__PROJECT_NAME__/g, this.projectName);
		result = result.replace(/\/\/__INTERFACE_METHODS__/, this.generateInterfaceMethods(viewControllerData));
		
		var outletsCode = this.generateCodeForOutlets(viewControllerData);
		result = result.replace(/\/\/__INTERFACE_BODY__\n/, outletsCode);
		
		result = result.replace(/\/\/__INTERFACE_HEADER_IMPORTS__\n/, this.generateHeaderImports(
			this.includeHeadersForVCData(viewControllerData),
			this.classNamesWithoutHeaderForVCData(viewControllerData)
		));

		return result;};
	
	
iOSAppGenerator.prototype.generateHeaderImports = function iOSAppGenerator__generateHeaderImports(headerObj, classNamesObj) {
	
		var lines = [];
		
		for (var h in headerObj) {
			lines.push('#import "'+h+'"\n');
		}
		
		for (var n in classNamesObj) {
			lines.push('@class '+n+';\n');
		}
		
		return lines.join("");};
	
	
iOSAppGenerator.prototype.generateImplementationIvars = function iOSAppGenerator__generateImplementationIvars() {
		if (!Object.keys(this.implementationIvars).length) return '';
		var lines = [];
		
		for (var name in this.implementationIvars) {
			lines.push('	'+this.implementationIvars[name]+' '+name+';');
		}
		
		return ' {\n'+lines.join('\n')+'\n}';};
	

iOSAppGenerator.prototype._generateViewControllerImplementationFile = function iOSAppGenerator___generateViewControllerImplementationFile(classId, viewControllerData, templateName) {
	
		this.includeHeaders = {};
		this.implementationIvars = {};
		
		var body	= this.generateImplementationMethods(viewControllerData);
		var imports	= this.generateHeaderImports(this.includeHeadersForVCData(viewControllerData, true));
		var ivars 	= this.generateImplementationIvars();
	
		var result = this._getTemplate(templateName, 'implementation');
		
		result = result.replace(/__UIVIEWCONTROLLER_CLASS__/g, classId);
		result = result.replace(/__PROJECT_NAME__/g, this.projectName);
		
		result = result.replace(/\/\/__IMPLEMENTATION_HEADER_IMPORTS__\n/, imports);
		result = result.replace(/\/\/__IMPLEMENTATION_IVARS__/, ivars);
		result = result.replace(/\/\/__IMPLEMENTATION_BODY__\n/, body);
		
		return result;};
	
	
iOSAppGenerator.prototype.NSDictionaryFromObject = function iOSAppGenerator__NSDictionaryFromObject(obj) {
		
		if (!obj) return 'nil';
		
		var result = '';
		for (var key in obj) {
			if (typeof obj[key] !== 'string') continue;
			result += this.ObjCStringify(obj[key])+', '+this.ObjCStringify(key)+', ';
		}

		if (!result) return '[NSDictionary dictionary]';
		
		result = '[NSDictionary dictionaryWithObjectsAndKeys:'
			+ result
			+ 'nil]';
		
		return result;
		};
	
	
iOSAppGenerator.prototype.ObjCStringify = function iOSAppGenerator__ObjCStringify(str) {
		var v = JSON.stringify(str);
		if (!v || v[0] !== '"' || v[v.length-1] !== '"') v = '""';
		return '@'+v;};
	
	
iOSAppGenerator.prototype.transformString = function iOSAppGenerator_transformString(str) {
		return this.ObjCStringify(str);};
	

iOSAppGenerator.prototype.transformNumber = function iOSAppGenerator_transformNumber(value) {
		if (typeof value === 'number') return value;
		return parseFloatLocal(value)||0;};
	
	
iOSAppGenerator.prototype.hexStringFromCSSColor = function iOSAppGenerator__hexStringFromCSSColor(cssColor) {
	
		if (!cssColor) return '00000000';
	
		var data = this.transformCSSColor(cssColor, null);
		
		if (data.colorSpace === 'calibratedWhite') {
			return rgba2hex(data.white*255,data.white*255,data.white*255,data.alpha*255);
		}

		if (data.colorSpace === 'calibratedRGB') {
			return rgba2hex(data.red*255,data.green*255,data.blue*255,data.alpha*255);
		}
		
		if (data.colorSpace === 'deviceRGB')  {
			var converted = convertLinearRGBToSRGB(data);
			return rgba2hex(converted.red*255,converted.green*255,converted.blue*255,converted.alpha*255);
		}
		
		 console.error('Unsupported color space:', data);
		
		return '';
	};
	
	
iOSAppGenerator.prototype.stringFromCSSColor = function iOSAppGenerator__stringFromCSSColor(cssColor) {

		if (!cssColor) return '';
		var data = this.transformCSSColor(cssColor, null);
		return JSON.stringify(data);
	};
	
	
iOSAppGenerator.prototype.UIColorFromCSSColor = function iOSAppGenerator__UIColorFromCSSColor(cssColor) {
	
		if (!cssColor) return 'nil';
	
		var data = this.transformCSSColor(cssColor, null);
		
		if (data.colorSpace === 'calibratedWhite') {
			return '[UIColor colorWithWhite:'+data.white+' alpha:'+data.alpha+']';
		}

		if (data.colorSpace === 'calibratedRGB') {
			if (data.red == 1 && data.green == 1 && data.blue == 1 && data.alpha == 1) return '[UIColor whiteColor]';
			if (data.red == 0 && data.green == 0 && data.blue == 0 && data.alpha == 1) return '[UIColor blackColor]';
			if (data.red == 1 && data.green == 0 && data.blue == 0 && data.alpha == 1) return '[UIColor redColor]';
			if (data.red == 1 && data.green == 0 && data.blue == 0 && data.alpha == 1) return '[UIColor greenColor]';
			if (data.red == 0 && data.green == 0 && data.blue == 1 && data.alpha == 1) return '[UIColor blueColor]';
			return '[UIColor colorWithRed:'+data.red+' green:'+data.green+' blue:'+data.blue+' alpha:'+data.alpha+']';
		}
		
		if (data.colorSpace === 'deviceRGB')  {
			var converted = convertLinearRGBToSRGB(data);
			return '[UIColor colorWithRed:'+converted.red+' green:'+converted.green+' blue:'+converted.blue+' alpha:'+converted.alpha+']';
		}
		
		 console.error('Unsupported color space:', data);
		 return '/* Unsupported color space*/ nil';};
	
	
iOSAppGenerator.prototype.transformCSSColor = function iOSAppGenerator_transformCSSColor(color, key) {
	
		return _context.colorInfoFromCSSColor(color, key);
	};
	


	

iOSAppGenerator.prototype._generateTableViewCellFiles = function iOSAppGenerator___generateTableViewCellFiles(classId, result) {

		var cellData = this.tableViewCells[classId];

		result[this.projectName+'/'+classId+'.h'] =
			this._generateTableViewCellHeaderFile(classId, cellData);

		result[this.projectName+'/'+classId+'.m'] =
			this._generateTableViewCellImplementationFile(classId, cellData);};
	

iOSAppGenerator.prototype._generateTableViewCellHeaderFile = function iOSAppGenerator___generateTableViewCellHeaderFile(classId, cellData) {
		return this._generateCellHeaderFile(classId, cellData, 'UITableViewCell');};
	

iOSAppGenerator.prototype._generateTableViewCellImplementationFile = function iOSAppGenerator___generateTableViewCellImplementationFile(classId, cellData) {
		return this._generateCellImplementationFile(classId, cellData, 'Cell');};
	
	
iOSAppGenerator.prototype._insertCustomAccessoryViewImplementationCode = function iOSAppGenerator___insertCustomAccessoryViewImplementationCode(result, cellData) {
	
		if (!cellData.tableViewData) return result;
		
		if (cellData.tableViewData.colorScheme === 'dark') {
			result = result.replace(/\/\/__MODULE_CUSTOM_ACCESSORY_VIEW_IMPORT__/, '#import "ASColoredDisclosureIndicator.h"');
			result = result.replace(/\/\/__MODULE_CUSTOM_ACCESSORY_VIEW_SETUP__/, '- (void)awakeFromNib {\n\
	self.accessoryView = [ASColoredDisclosureIndicator accessoryWithColor:[UIColor colorWithWhite:1 alpha:0.5]];\n\
}\n');
		}
		else {
			result = result.replace(/\/\/__MODULE_CUSTOM_ACCESSORY_VIEW_IMPORT__/, '');
			result = result.replace(/\/\/__MODULE_CUSTOM_ACCESSORY_VIEW_SETUP__/, '');
		}
		
		return result;};
	

iOSAppGenerator.prototype._insertCellBackgroundColorImplementationCode = function iOSAppGenerator___insertCellBackgroundColorImplementationCode(result, cellData) {
		
		var color;
		try {
			color = this.UIColorFromCSSColor(
				cellData.originalData.style.backgroundColor);
		} catch (err) {
			color = '[UIColor clearColor]';
		}

		result = result.replace(/__CELL_BACKGROUND_COLOR__/, color);
		
		return result;};
	

	

iOSAppGenerator.prototype._generateCollectionViewCellFiles = function iOSAppGenerator___generateCollectionViewCellFiles(classId, result) {

		var cellData = this.collectionViewCells[classId];

		result[this.projectName+'/'+classId+'.h'] =
			this._generateCellHeaderFile(classId, cellData, 'UICollectionViewCell');

		result[this.projectName+'/'+classId+'.m'] =
			this._generateCellImplementationFile(classId, cellData, 'Cell');};
	

iOSAppGenerator.prototype._generateCellHeaderFile = function iOSAppGenerator___generateCellHeaderFile(classId, cellData, templateName) {
		var result = this._getTemplate(templateName, 'header');
		result = result.replace(/__CELL_CLASS__/g, classId);
		result = result.replace(/__PROJECT_NAME__/, this.projectName);
		var outletsCode = this.generateCodeForOutlets(cellData);
		result = result.replace(/\/\/__INTERFACE_BODY__\n/, outletsCode);
		result = result.replace(/\/\/__INTERFACE_HEADER_IMPORTS__\n/, this.generateHeaderImports(this.includeHeadersForCellData(cellData)));

		return result;};
	

iOSAppGenerator.prototype._generateCellImplementationFile = function iOSAppGenerator___generateCellImplementationFile(classId, cellData, templateName) {

		var result = this._getTemplate(templateName, 'implementation');
		result = result.replace(/__CELL_CLASS__/g, classId);
		result = result.replace(/__PROJECT_NAME__/, this.projectName);

		
		result = result.replace(/\/\/__OUTLETS_CONFIGURE_WITH_DATASET__/, this.generateOutletConfigurationWithDatasetCode(cellData));

		
		result = result.replace(/\/\/__OUTLETS_CONFIGURE_FOR_LAYOUT__/, this.generateLayoutCode(cellData));

		
		result = result.replace(/\/\/__IMPLEMENTATION_HEADER_IMPORTS__\n/, this.generateHeaderImports(this.includeHeaders));

		result = this._insertCustomAccessoryViewImplementationCode(result, cellData);
		result = this._insertCellBackgroundColorImplementationCode(result, cellData);

		var methods = {};
		var allObjects = this.allObjectsForCell(cellData);

		this.addMethodsForObjects(allObjects, methods);

		var body	= this.generateStringFromMethods(methods);
		result = result.replace(/\/\/__IMPLEMENTATION_BODY__\n/, body);

		return result;
	};
	
	
	
	
	
iOSAppGenerator.prototype.registerResourceUsage = function iOSAppGenerator_registerResourceUsage(fileReference, context) {
		if (!this.fileReferenceUsage) this.fileReferenceUsage = {};
		if (!this.fileReferenceUsage[fileReference.$id]) this.fileReferenceUsage[fileReference.$id] = 0;
		this.fileReferenceUsage[fileReference.$id]++;};
	
	
iOSAppGenerator.prototype.getUsageCountForFileReference = function iOSAppGenerator_getUsageCountForFileReference(fileReference) {
		if (!this.fileReferenceUsage) return 0;
		return this.fileReferenceUsage[fileReference.$id] || 0;};
	

iOSAppGenerator.prototype.pathForPluginFile = function iOSAppGenerator__pathForPluginFile(relativePath, plugin, pluginIdentifier) {

		if (this.keepPluginReferences) {
			var path = plugin.path+'/Product/'+relativePath;
			return path.replace('/Bundle/PlugIns','/appdoo Mac/PlugIns');
		}

		return pluginIdentifier+'/'+relativePath;};
	


	

iOSAppGenerator.prototype._generatePbxFile = function iOSAppGenerator___generatePbxFile(generatedFiles, referencedFiles) {

		var resources = [];
		var projectFiles = [];
		var metadata = _context.projectContext.metadata;
























		
		
		
		resources.push({ name: "Images.xcassets", contentType: '' });
		projectFiles.push("Images.xcassets");
		
		this.images.every(function (imageName) {
			
		
			var pathExtension = getPathExtension(imageName);

			resources.push({
				name: imageName,
				contentType: 'image/'+pathExtension
			});
			projectFiles.push(imageName);
			return true;
		}.bind(this));
		
		








































		
		var resourcesToSkip = [];
		
		
		
		if (metadata.iconImage && metadata.iconImage.fileReferenceID) {
			var ref = _context.projectContext.fileReferenceWithID(metadata.iconImage.fileReferenceID);
			if (this.getUsageCountForFileReference(ref) < 1) {
				resourcesToSkip.push(ref.name);
			}
		}

		this.resources.every(function (item) {
			if (!this.resourceItemIsValid(item)) {
				console.warn('Invalid resource item detected, skipping.', item);
				return true;
			}
			if (resourcesToSkip.indexOf(item.name) !== -1) return true;
			resources.push(item);
			projectFiles.push(item.name);
			return true;
		}.bind(this));
	
		var data = {
			template: this.getCodeGenerationTemplate('PbxTemplate.txt'),
			projectName: this.projectName,
			headerFiles: [],
			implementationFiles: [],
			resources: resources,
			systemFrameworks: {},
			systemLibraries: {},
			localizedStringFiles: {},
			supportingFiles: [],
			projectFiles: projectFiles,
			pluginFiles: {}
		};

		for (var codeID in this.viewControllers) {
			data.headerFiles.push(codeID+'.h');
			data.implementationFiles.push(codeID+'.m');
			data.projectFiles.push(codeID+'.h', codeID+'.m');
		}

		for (var key in this.tableViewCells) {
			data.headerFiles.push(key+'.h');
			data.implementationFiles.push(key+'.m');
			data.projectFiles.push(key+'.h', key+'.m');
		}

		for (var key in this.collectionViewCells) {
			data.headerFiles.push(key+'.h');
			data.implementationFiles.push(key+'.m');
			data.projectFiles.push(key+'.h', key+'.m');
		}
		


		for (var pluginIdentifier in this.plugins) {
			var plugin = window.availablePlugins[pluginIdentifier];
			var pluginFiles = [];

			if (Array.isArray(plugin.buildFiles)) plugin.buildFiles.every(function (f) {
				var path = this.pathForPluginFile(f, plugin, pluginIdentifier);
				data.implementationFiles.push(path);
				pluginFiles.push(path);return true; }, this);
			
			if (Array.isArray(plugin.headerFiles)) plugin.headerFiles.every(function (f) {
				var path = this.pathForPluginFile(f, plugin, pluginIdentifier);
				data.headerFiles.push(path);
				pluginFiles.push(path);return true; }, this);
			
			for (var f in plugin.systemFrameworks) {
				data.systemFrameworks[f] = true;
			}
			for (var f in plugin.systemLibraries) {
				data.systemLibraries[f] = true;
			}
			for (var f in plugin.localizedStringFiles) {
				data.localizedStringFiles[f] = {
					directoryPath: pluginIdentifier,
					languageCodes: plugin.localizedStringFiles[f]
				};
				pluginFiles.push(f);
			}
			if (Array.isArray(plugin.resources)) plugin.resources.every(function (pluginResource) {
				data.resources.push(pluginResource);
				pluginFiles.push(pluginResource.name||pluginResource.path);return true; }, this);
			
			if (plugin.includeHeader && !(plugin.headerFiles && plugin.headerFiles.indexOf(plugin.includeHeader) !== -1)) {
				var path = this.pathForPluginFile(plugin.includeHeader, plugin, pluginIdentifier);
				data.headerFiles.push(path);
				pluginFiles.push(path);
			}
			
			data.pluginFiles[pluginIdentifier] = pluginFiles;

			this.payload.files.push(this.projectName+'/'+pluginIdentifier);
			
			if (plugin.licenceFile)
				this.licencedPlugins.push(pluginIdentifier);
			
		}
		
		if (Array.isArray(resources)) resources.every(function (resource) {
			
			if (typeof resource.name !== 'string' || resource.name.indexOf('/') !== -1) return true;
			
			this.payload.files.push(this.projectName+'/'+resource.name);return true; }, this);
		
		
		if (Array.isArray(referencedFiles)) referencedFiles.every(function (filePath) {
			var fileExtension = getPathExtension(filePath);
			if (fileExtension === 'h') data.headerFiles.push(filePath);
			if (fileExtension === 'm') data.implementationFiles.push(filePath);
			this.payload.referencedFiles.push(filePath);return true; }, this);
		
		
		var defaultLanguage = metadata.defaultLanguage;

		if (defaultLanguage) {
			data.localizedStringFiles['InfoPlist.strings'] = {
					directoryPath: '',
					languageCodes: [defaultLanguage]
				};
			var innerPath = defaultLanguage+'.lproj/InfoPlist.strings';
			data.supportingFiles.push('InfoPlist.strings');
			generatedFiles[this.projectName+'/'+innerPath] = '';
		}


		generatedFiles[this.projectName+'.xcodeproj/project.pbxproj'] =
			this.pbxFileGenerator.generateFromData(data, this.originalData, this);
			};
	
		
	
	function getPathExtension(path) {
		if (!path) return '';
		if (path.indexOf('.') === -1) return '';
		return path.split('.').pop();
	}
	
iOSAppGenerator.prototype._generateInfoPlistFile = function iOSAppGenerator___generateInfoPlistFile(files, data) {

		var src = this._getTemplate('Info','plist');
		var companyIdentifier = (data.metadata.companyName||'com.mycompany');
		var companyIdentifierClean = companyIdentifier.replace(/([^a-z0-9.]+)/gi, '-');
		src = src.replace(/__COMPANY_IDENTIFIER__/, companyIdentifierClean.toLowerCase());
		src = src.replace(/__APP_VERSION_SHORT__/g, (data.metadata.version||'1.0'));
        src = src.replace(/__APP_VERSION__/g, (data.metadata.build||'1'));
		src = src.replace(/__APP_CATEGORY__/, (data.metadata.appleAppCategory||''));
		
		
		src = src.replace(/__ICON_CODE__/, '');















		
		var key = 'UISupportedInterfaceOrientations';
		if (this.targetDeviceIsIPad) key += '~ipad';

		var UIInterfaceOrientationMaskPortrait = 1 << 1,
			UIInterfaceOrientationMaskPortraitUpsideDown = 1 << 2,
			UIInterfaceOrientationMaskLandscapeLeft = 1 << 3,
			UIInterfaceOrientationMaskLandscapeRight = 1 << 4;
		
		var backgroundModesCode = [
		'	<key>UIBackgroundModes</key>',
		'	<array>',
		];
		if (data.metadata.requiresBackgroundAudioPlayback) {
			backgroundModesCode.push(
			'		<string>audio</string>'
			);
		}
		backgroundModesCode.push(
		'	</array>'
		);
		
		var interfaceOrientationCode = [
		'	<key>'+key+'</key>',
		'	<array>',
		];
		if ((data.metadata.supportedInterfaceOrientations & UIInterfaceOrientationMaskPortrait) !== 0) {
			interfaceOrientationCode.push(
			'		<string>UIInterfaceOrientationPortrait</string>'
			);
		}
		if ((data.metadata.supportedInterfaceOrientations & UIInterfaceOrientationMaskPortraitUpsideDown) !== 0) {
			interfaceOrientationCode.push(
			'		<string>UIInterfaceOrientationPortraitUpsideDown</string>'
			);
		}
		if ((data.metadata.supportedInterfaceOrientations & UIInterfaceOrientationMaskLandscapeLeft) !== 0) {
			interfaceOrientationCode.push(
			'		<string>UIInterfaceOrientationLandscapeLeft</string>'
			);
		}
		if ((data.metadata.supportedInterfaceOrientations & UIInterfaceOrientationMaskLandscapeRight) !== 0) {
			interfaceOrientationCode.push(
			'		<string>UIInterfaceOrientationLandscapeRight</string>'
			);
		}
		interfaceOrientationCode.push(
		'	</array>'
		);
		
		interfaceOrientationCode.push(backgroundModesCode.join('\n'));
		src = src.replace(/__INTERFACE_ORIENTATION_CODE__/, interfaceOrientationCode.join('\n'));

		src = src.replace(/__DISPLAY_NAME__/, data.metadata.title);
		
		var optionalConfiguration = '';
		
		optionalConfiguration += '	<key>UIRequiresFullScreen</key>\n	<true/>\n';

		if (data.metadata.hidesStatusBarOnLaunch && parseInt(data.metadata.hidesStatusBarOnLaunch) > 0) {
			this.hidesStatusBarOnLaunch = parseInt(data.metadata.hidesStatusBarOnLaunch);
			optionalConfiguration += '	<key>UIStatusBarHidden</key>\n	<true/>\n';
		}
		
        if (data.metadata.statusBarStyle && parseInt(data.metadata.statusBarStyle) > 0) {
            this.statusBarStyle = parseInt(data.metadata.statusBarStyle);
            optionalConfiguration += '    <key>UIViewControllerBasedStatusBarAppearance</key>\n    <false/>\n';
            if(parseInt(data.metadata.statusBarStyle) == 2) {
                optionalConfiguration += '    <key>UIStatusBarStyle</key>\n    <string>UIStatusBarStyleDarkContent</string>\n';
            } else if(parseInt(data.metadata.statusBarStyle) == 1) {
                optionalConfiguration += '    <key>UIStatusBarStyle</key>\n    <string>UIStatusBarStyleLightContent</string>\n';
            } else {
                optionalConfiguration += '    <key>UIStatusBarStyle</key>\n    <string>UIStatusBarStyleDefault</string>\n';
            }
        } else {
            optionalConfiguration += '    <key>UIViewControllerBasedStatusBarAppearance</key>\n    <true/>\n';
        }
        
		var allFonts = [];
		if (Array.isArray(this.context.projectContext.fileReferences)) this.context.projectContext.fileReferences.every(function (ref) {
			if (!ref.isFont) return true;
			allFonts.push(ref);return true; }, this);
		
		
		if (allFonts.length) {
			optionalConfiguration += '	<key>UIAppFonts</key>\n	<array>\n';
			if (Array.isArray(allFonts)) allFonts.every(function (font) {
				optionalConfiguration += '		<string>'+font.name+'</string>\n';return true; }, this);
			
			optionalConfiguration += '\n	</array>\n';
		}

		src = src.replace(/__OPTIONAL_CONFIGURATION__/, optionalConfiguration);

		files[this.projectName+'/'+this.projectName+'-Info.plist'] = src;};
	


	
	
iOSAppGenerator.prototype.outletNameIsValid = function iOSAppGenerator_outletNameIsValid(outletName) {
		if (outletName === 'switch') return false;
		return true;
	}
	
iOSAppGenerator.prototype.pluginIdentifierForData = function iOSAppGenerator_pluginIdentifierForData(data) {
		var proto = this.prototypeFromData(data);
		if (proto && proto.pluginIdentifier) return proto.pluginIdentifier;
		return utiFromData(data);};
	
	
iOSAppGenerator.prototype.prepareGlobalObjects = function iOSAppGenerator__prepareGlobalObjects(objects) {

		if (Array.isArray(objects)) objects.every(function (obj) {
			this.reserveOutletName(obj);return true; }, this);
		
	};
	
	
iOSAppGenerator.prototype.reserveOutletName = function iOSAppGenerator__reserveOutletName(obj) {
	
		if (this.outletNameForProjectID[obj.$id]) return this.outletNameForProjectID[obj.$id];
		var outletNames = this.globalOutletNames;
		
    	var outletName = this.generateOutletName(obj);
    	var i = 1, outletNameCopy = outletName;
    	if (!this.outletNameIsValid(outletName)) outletName = outletNameCopy+'1';
    	while (outletNames.indexOf(outletName) !== -1 || !this.outletNameIsValid(outletName)) {
    		i++;
    		outletName = outletNameCopy+i;
    	}
    	outletNames.push(outletName);
    	
    	this.outletNameForProjectID[obj.$id] = outletName;
    	return outletName;
			};
	

iOSAppGenerator.prototype._generateAppDelegate = function iOSAppGenerator___generateAppDelegate(data, files) {

		this.isTransformingAppDelegate = true;
		this.includeHeaders = {};
		this.implementationIvars = {};
		

		var source = this.getCodeGenerationTemplate('AppDelegate.h');
		source = source.replace(/__PROJECT_NAME__/g, this.projectName);

		var outlets = {};
		
		if (Array.isArray(data.objects)) data.objects.every(function (obj) {
			handleObject.call(this, obj);
			
			if(obj["$type"] = "SceneInputDataSource") {
				var missingHeaderFile = obj["$type"] + ".h"
				this.includeHeadersForThing['AppDelegate'][missingHeaderFile] = obj["$id"];
			}return true; }, this);
		

		if (Array.isArray(this.globalInlineObjects)) this.globalInlineObjects.every(function (obj) {
			handleObject.call(this, obj);return true; }, this);
		
		
		function handleObject(obj) {
			if (utiFromData(obj) === 'info.appdoo-mac.PerformSelectorInstruction') {
				alertd("utiFromData(obj) === 'info.appdoo-mac.PerformSelectorInstruction'");
				return;
			}
			var proto = this.storyboardTransformer.prototypeFromData(obj);
			
			var shouldHaveOutlet = (function (o, proto) {
			
				if (proto.needsNoObjCOutlet) return false;
				if (proto.needsNoObjCOutletForInstance) return !proto.needsNoObjCOutletForInstance(o);
				return true;
				
			}(obj, proto));
			
			if (shouldHaveOutlet) {
			
				var outletName = this.outletNameForProjectID[obj.$id];
				outlets[outletName] = { className: this.storyboardTransformer.cocoaTypeForData(obj, proto), customClass: this.storyboardTransformer.cocoaCustomTypeForData(obj, proto) };
				
			}
			
			if (proto.isPlugin) {
				this.registerObjectWithPluginIdentifier(obj, this.pluginIdentifierForData(proto), null, null, {$id:'AppDelegate'});
			}
		}

		var interfaceBody = this.generateCodeForOutlets({ outlets: outlets }, true);

		if (this.overwritesModalInterfaceOrientations) {
			interfaceBody += '@property NSUInteger currentSupportedInterfaceOrientations;\n';
		}
		source = source.replace(/\/\/__INTERFACE_BODY__\n/, interfaceBody);

		source = source.replace(/\/\/__INTERFACE_HEADER_IMPORTS__\n/, this.generateHeaderImports(this.includeHeadersForAppDelegate()));
		
		files[this.projectName+'/AppDelegate.h'] =
			source;


		this.includeHeaders = {};

		var source = this.getCodeGenerationTemplate('AppDelegate.m');
		var allObjects = this.allGlobalObjects();
		
		source = source.replace(/__PROJECT_NAME__/g, this.projectName);
		var dict = this.generateBindingsDictionaryForObjects(allObjects);
		var body	= this.generateAppDelegateImplementationMethods(allObjects, dict, data);
		var ivars 	= this.generateImplementationIvars();
		source = source.replace(/\/\/__IMPLEMENTATION_BODY__\n/, body);
		source = source.replace(/\/\/__IMPLEMENTATION_IVARS__/, ivars);
		
		var imports	= this.generateHeaderImports(this.includeHeadersForAppDelegate(true));
		source = source.replace(/\/\/__IMPLEMENTATION_HEADER_IMPORTS__\n/, imports);
		
		
		files[this.projectName+'/AppDelegate.m'] =
			source;

		this.isTransformingAppDelegate = false;

};
	

	
	
	var fileExtensionForRole = {
		'header': 'h',
		'implementation': 'm',
		'plist': 'plist'
	};
	
iOSAppGenerator.prototype.getCodeGenerationTemplate = function iOSAppGenerator__getCodeGenerationTemplate(filename) {
		return this.context.nativeProxy.sendMessage('stringFromBundleFile', 'TemplatesExport/iOS.appdoocg/File Templates/'+filename);};
	

iOSAppGenerator.prototype._getTemplate = function iOSAppGenerator___getTemplate(id, role) {
	
		var template = this.getCodeGenerationTemplate(id+'.'+fileExtensionForRole[role]);
	
		if (!template) {
			 console.error('Template not found:', id, role);
			return;
		}
		
		return template;};
	


	
	
iOSAppGenerator.prototype.generateOutletConfigurationWithDatasetCode = function iOSAppGenerator__generateOutletConfigurationWithDatasetCode(data) {
	
		function destinationKeyPathForBinding(binding) {
			var destinationKeyPath = binding.destinationKeyPath;
			if (destinationKeyPath.indexOf('contents.') === 0) {
				destinationKeyPath = destinationKeyPath.substr('contents.'.length);
			}
			return destinationKeyPath;	
		}
		

		var generatedCode = '';
		var numberOfBindings = 0;
		for (var key in data.outlets) {
			var outlet = data.outlets[key];
			var proto = prototypeFromData(outlet.originalData);
			
			if (outlet.bindings)
			outlet.bindings.every(function (binding) {
				var destinationKeyPath = destinationKeyPathForBinding(binding);
			
				if (destinationKeyPath === '^NULL^') return true;

				var propertyType = propertyTypeInObject(binding.sourceKeyPath, proto, outlet.originalData);
				if (!propertyType) return true;
				
				var valueTransformer = valueTransformerForPropertyType(propertyType, binding);
				
				var value;
				if (destinationKeyPath) value = '_inputDataIsDictionary ? [_inputData valueForKeyPath:@"'+destinationKeyPath+'"] : nil';
				else value = '_inputData';
				
				generatedCode += '	self.'+key+'.'+binding.sourceKeyPath+' = ';
				
				var transformerCall = '[BindingsHandler transformValue:('+value+') withTransformer:@"'+valueTransformer+'"]';
	
				if (valueTransformer === 'TO_BOOLEAN' || valueTransformer === 'TO_INVERTED_BOOLEAN')
					transformerCall = '['+transformerCall+' boolValue]';
				
				generatedCode += transformerCall+';\n';
				
				if (binding.sourceKeyPath === 'imageURLString') {
					this.demandPluginWithIdentifier('info.appdoo-mac.UIImageView+URL', data);
					this.demandPluginWithIdentifier('info.appdoo-mac.NSStringPunycodeAdditions', data);
				}
				
				numberOfBindings++;
								
				return true;
			}.bind(this));
		}
		if (numberOfBindings) {
			this.demandPluginWithIdentifier('info.appdoo-mac.BindingsHandler', data);
		}
		
		if (data.sourceSceneData) {
			var nb = data.sourceSceneData.navigationBar;
			if (nb) {
				if (Array.isArray(nb.bindings)) nb.bindings.every(function (binding) {

					var destinationKeyPath = destinationKeyPathForBinding(binding);

					if (binding.sourceKeyPath === 'title') {
						generatedCode += '	self.navigationItem.title = [_inputData valueForKeyPath:@"'+destinationKeyPath+'"];\n';
					}return true; }, this);
				
			}
		}
		
		return generatedCode;
	};
	

iOSAppGenerator.prototype.generatePostBindingsCode = function iOSAppGenerator__generatePostBindingsCode(data) {
		var code = '';
		if (data.sourceSceneData) {
			if (Array.isArray(data.sourceSceneData.objects)) data.sourceSceneData.objects.every(function (object) {
				if (object.generatePostBindingsCodeFromData)
					code += (object.generatePostBindingsCodeFromData(object, this.storyboardTransformer)||'')+'\n';return true; }, this);
			
		}
		return code;};
	
	
iOSAppGenerator.prototype.generateLayoutCode = function iOSAppGenerator__generateLayoutCode(data) {
	
		

		
		if (!data.originalData) return '';
		
		var code = '';
		var originalView = data.originalData.viewData || data.originalData;
		var typeFromData = this.typeFromData;
		
		function processView(view) {

			if (Array.isArray(view.subviews)) view.subviews.every(function (subview) {
				var subviewType = typeFromData.call(this,subview);
				if (subviewType && subviewType.prototype.generateLayoutCodeFromData) {
					var codePath = this.codePathForProjectID(subview.$id);
					if (codePath)
						code += subviewType.prototype.generateLayoutCodeFromData(subview, codePath, this) || '';
				}

				if (subview.subviews) processView.call(this, subview);return true; }, this);
			

		}
		
		processView.call(this, originalView);
		
		var layoutRelations = getType('appdoo.Editor.LayoutResolver').prototype.sortedLayoutRelationsForView(originalView, this.context.projectContext);
		
		if (layoutRelations.length) {

			code += '	if (!self.layoutConstraints) self.layoutConstraints = @[\n';
			
			if (Array.isArray(layoutRelations)) layoutRelations.every(function (lr) {
				var subjectOutletName = this.outletNameForProjectID[lr.source],
					objectOutletName = this.outletNameForProjectID[lr.destination];
	
				var globalObject = this.subviewWithID(lr.source);
				if(globalObject && globalObject.$type && globalObject.$type == "UITableView" && (!globalObject.usesDataSource || globalObject.usesDataSource !== true)) {
					subjectOutletName = "embeddedViewController."+subjectOutletName+".superview";
				}
				if (!subjectOutletName || !objectOutletName) {
					console.warn('Missing an outlet for a layout relation:', lr, subjectOutletName, objectOutletName);
					return true;
				}
				
				code += '\t\t\t\t@{@"subject":self.'+subjectOutletName+', @"object":self.'+objectOutletName+', @"type":'+this.ObjCStringify(lr.type)+', @"offset":@'+(lr.offset || 0)+'},\n';return true; }, this);
			
			
			var viewProperty = data.originalData.viewData ? 'self.contentView' : 'self';
	
			code += '\t\t\t\t];\n\t[LayoutResolver layoutView:'+viewProperty+' constraints:self.layoutConstraints];\n';
		
		}

		if (!code) return '';
		return code;
};
	

iOSAppGenerator.prototype.generateCodeForOutlets = function iOSAppGenerator__generateCodeForOutlets(data, strong) {
	
		var weakOrStrong = strong ? 'strong' : 'weak';

		var lines = [];

		for (var key in data.outlets) {
			var outlet = data.outlets[key];
			var t = (outlet.customClass || outlet.className);
			if (t !== 'id') t += ' *';
			var _weakOrStrong = weakOrStrong;
			if (key === 'tableView') _weakOrStrong = 'strong';
			lines.push('@property ('+_weakOrStrong+', nonatomic) IBOutlet '+t+' '+key+";\n");
		}

		for (var key in data.otherProperties) {
			var p = data.otherProperties[key];
			weakOrStrong = p.weakOrStrong || 'weak';
			var t = p.type;
			if (t !== 'id') t += ' *';
			lines.push('@property ('+weakOrStrong+', nonatomic) '+t+' '+key+";\n");
		}
		
		return lines.join("");
	};
	
	
iOSAppGenerator.prototype._insertViewControllerDatasetConfigurationCode = function iOSAppGenerator___insertViewControllerDatasetConfigurationCode(result, data) {
		var generatedCode = '';
		
		var bindings = data.originalData.bindings;
		if (bindings && bindings.length) {
			var binding = bindings[0];
			if (binding.sourceKeyPath === 'navigationBarTitle')
				generatedCode += '	self.title = [dataset objectForKey:@"'+binding.destinationKeyPath+'"];';
		}
	
		result = result.replace(/\/\/__VIEW_CONTROLLER_CONFIGURE_WITH_DATASET__/, generatedCode);
	
		return result;};
	

iOSAppGenerator.prototype._configurePluginObjects = function iOSAppGenerator___configurePluginObjects(result) {
	
		var pcc = createComponentFromDomain("PluginCodeConfigurator", "appdoo.iOSGenerator", this.context, {})
		;
		pcc.files = result.generatedFiles;
		pcc.productGenerator = this;
		
		if (Array.isArray(this.pluginObjects)) this.pluginObjects.every(function (obj) {
			obj.symbol = this.outletNameForProjectID[obj.data.$id];
			pcc.configureObject(obj);return true; }, this);
		

		result.generatedFiles = pcc.files;
};
	
	
iOSAppGenerator.prototype.imageRefIsValid = function iOSAppGenerator__imageRefIsValid(imageRef) {
		return imageRef && imageRef.imageID && this.imageIsValid(imageRef.imageID);};
	
	
iOSAppGenerator.prototype.imageIsValid = function iOSAppGenerator__imageIsValid(imageId) {
		var isValid = !!this.context.nativeProxy.sendMessage('pathForImageWithID', imageId);
		return isValid;};
	

iOSAppGenerator.prototype.staticDataSourceIsValid = function iOSAppGenerator__staticDataSourceIsValid(dataSource) {
		var isValid = !!this.context.nativeProxy.sendMessage('pathForDatabaseWithID', dataSource.$id);
		return isValid;};
	
	
iOSAppGenerator.prototype.resourceItemIsValid = function iOSAppGenerator__resourceItemIsValid(resourceItem) {
		var isValid = !!this.context.nativeProxy.sendMessage('pathForResourceReferenceFile', JSON.stringify(resourceItem));
		return isValid;};
	
	
iOSAppGenerator.prototype.allObjectsForScene = function iOSAppGenerator_allObjectsForScene(originalScene) {
		return (originalScene.objects||[]).concat(this.inlineObjectsForOriginalSceneID[originalScene.$id]||[]);};
	

iOSAppGenerator.prototype.allObjectsForCell = function iOSAppGenerator_allObjectsForCell(originalCellViewData) {
		return this.inlineObjectsForCellViewCID[originalCellViewData.$id]||[];};
	
	
iOSAppGenerator.prototype.allGlobalObjects = function iOSAppGenerator_allGlobalObjects() {
		function mergeArrays(a, b) {
			var a = a.concat();                
			if(!b || !b.push || !b.length) return a;    
			if(!a.length) return b.concat();      
		
			
			for(var i = 0; i < b.length; i++){
				
				if(a.indexOf(b[i]) == -1) a.push(b[i]);
			}
			return a;
		}
	
		return mergeArrays(this.globalInlineObjects,this.originalData.objects);};
	


iOSAppGenerator.prototype.generateInterfaceMethods = function iOSAppGenerator__generateInterfaceMethods(viewControllerData) {
		var scene = viewControllerData.sourceSceneData;
		
		var result = '';
		
		var allObjects = this.allObjectsForScene(scene);
	
		if (Array.isArray(allObjects)) allObjects.every(function (obj) {
			if (!obj.isProcedure) return true;
			var selectorName = this.storyboardTransformer.selectorNameForProcedureID(obj.$id);
			result += '- (IBAction)'+selectorName+'(id)sender;\n\n';return true; }, this);
		

		return result;};
	
	
iOSAppGenerator.prototype.generateNavigationBarConfigurationCode = function iOSAppGenerator__generateNavigationBarConfigurationCode(scene) {

		if (!scene.e_showsNavigationBar) return '	[self.navigationController setNavigationBarHidden:YES animated:animated];';

		var navigationBarConfigurationCode = '	UINavigationBar * navigationBar = self.navigationController.navigationBar;\n';
		
		var navigationBarType = 'none';
		var barStyle = 'UIBarStyleDefault';
		
			if (scene.navigationBar.translucent) {
				navigationBarType = 'translucent';
			}
			else if (scene.navigationBar.tintColor) navigationBarType = 'custom';
			else if (scene.navigationBar.hidden) navigationBarType = 'none';
			else navigationBarType = 'default';
			
			barStyle = scene.navigationBar.barStyle === 1 ? 'UIBarStyleBlack':'UIBarStyleDefault';

		this.demandPluginWithIdentifier('info.appdoo-mac.UINavigationBarDefaultTint');
		
		var color = this.UIColorFromCSSColor(scene.navigationBar.tintColor);
		
		switch (navigationBarType) {
			case 'translucent':
				navigationBarConfigurationCode += '	[self.navigationController setNavigationBarHidden:NO animated:animated];\n\
\t[navigationBar memorizeDefaultTintColor];\n\
\tnavigationBar.tintColorOrUseDefault = '+color+';\n\
\tnavigationBar.translucent = YES;\n\
\tnavigationBar.barStyle = ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) ? '+barStyle+' : UIBarStyleBlack;';
				break;

			case 'custom':
			
			
			case 'colored': 
				
				navigationBarConfigurationCode += '	[self.navigationController setNavigationBarHidden:NO animated:animated];\n\
\tnavigationBar.tintColorOrUseDefault = '+color+';\n\
\tnavigationBar.barStyle = '+barStyle+';\n\
\tnavigationBar.translucent = NO;\n\
\tif ([navigationBar respondsToSelector:@selector(setBarTintColor:)]) [navigationBar setBarTintColor:'+this.UIColorFromCSSColor(scene.navigationBar.barTintColor)+'];\n';
				break;
				
			case 'default':
				navigationBarConfigurationCode += '	[self.navigationController setNavigationBarHidden:NO animated:animated];\n\
\tnavigationBar.tintColorOrUseDefault = nil;\n\
\tnavigationBar.barStyle = '+barStyle+';\n\
\tnavigationBar.translucent = NO;\n\
\tif ([navigationBar respondsToSelector:@selector(setBarTintColor:)]) [navigationBar setBarTintColor:'+this.UIColorFromCSSColor(scene.navigationBar.barTintColor)+'];\n';
				break;
				
			case 'none':
				navigationBarConfigurationCode += '	[self.navigationController setNavigationBarHidden:YES animated:animated];';
				break;
				
			default:
				navigationBarConfigurationCode = '';
		}


		if (scene.navigationBar.topItem) {
		
			if (scene.navigationBar.v_titleViewImage) {
				var imageName = this.handleInlineImage(scene.navigationBar.v_titleViewImage);
				if (imageName) navigationBarConfigurationCode += '\n	if (!self.navigationItem.titleView) self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"'+imageName+'"]];';
			}
			if (scene.navigationBar.v_backgroundImage) {
				var imageName = this.handleInlineImage(scene.navigationBar.v_backgroundImage);
				navigationBarConfigurationCode += '\
\t[navigationBar setBackgroundImage:[UIImage imageNamed:@"'+imageName+'"] forBarMetrics:UIBarMetricsDefault];';
			} else {
				navigationBarConfigurationCode += '\
\t[navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];';
			}
		}
		
		return navigationBarConfigurationCode;
	};
	

iOSAppGenerator.prototype.sceneHasASubviewThatMatchesConstraint = function iOSAppGenerator__sceneHasASubviewThatMatchesConstraint(scene, constraint, excludeStaticUITableViews, excludePrototypeCells) {
	
		var result;

		updateSubviewsWithCallback(scene.viewController.viewData, function (subview) {
			if (constraint(subview) === true) {
				result = true;
				return false;
			}
			else {
				return true;
			}
		}, excludeStaticUITableViews, excludePrototypeCells);
		
		return result;
		};
	
	
iOSAppGenerator.prototype.forEachSubviewInScene = function iOSAppGenerator__forEachSubviewInScene(scene, func, excludeStaticUITableViews, excludePrototypeCells) {

		updateSubviewsWithCallback(scene.viewController.viewData, func, excludeStaticUITableViews, excludePrototypeCells);
};
	
	
iOSAppGenerator.prototype.generateBindingsDictionaryForObjects = function iOSAppGenerator__generateBindingsDictionaryForObjects(objects) {
		var dict = {};
		if (Array.isArray(objects)) objects.every(function (obj) {
			collectBindingsForObject(obj, dict, this);return true; }, this);
		
		return dict;};
	
	
iOSAppGenerator.prototype.bindingIsValid = function iOSAppGenerator_bindingIsValid(binding) {
		var destinationCodePath = this.codePathForProjectID(binding.destination);
		return !!destinationCodePath;};
	
	
iOSAppGenerator.prototype.generateBindingsDictionaryForScene = function iOSAppGenerator__generateBindingsDictionaryForScene(scene) {
		var allObjects = this.allObjectsForScene(scene);
		return generateBindingsDictionaryForScene(scene, allObjects, this, this);};
	
	
iOSAppGenerator.prototype.controllerShouldObserveObject = function iOSAppGenerator__controllerShouldObserveObject(obj) {
		
		
		var result = (obj && (
			isKindOfType(obj, getType('appdoo.BasicDataSource')) ||
			isKindOfType(obj, getType('info.appdoo-mac.SearchBarDataProvider')) ||
			isKindOfType(obj, getType('info.appdoo-mac.TextFieldDelegate'))
			|| this.implementationHasObservable(obj)
		));
		alertd('result: ', result);
		return result;};
	
	
iOSAppGenerator.prototype.implementationHasObservable = function iOSAppGenerator__implementationHasObservable(obj) {
		return obj && typeof obj.implementationHasObservable == 'function' && obj.implementationHasObservable(obj);};
	

iOSAppGenerator.prototype.generateAddObserverCode = function iOSAppGenerator__generateAddObserverCode(dict) {
		var lines = [];
		for (var destinationObjectID in dict) {
			var obj = _context.projectContext.connectableObjects[destinationObjectID];
			if (!obj) {

				
				var viewData = (function findViewByID(id) {
					var found;
					_context.projectContext.scenes.every(function (scene) {
						function findRecursive(viewData) {
							if (viewData.$id == id) { found = viewData; }
							if (viewData.subviews) viewData.subviews.every(function (subviewData) {
								findRecursive(subviewData);
								if (!found) return true;
							});
						}
						findRecursive(scene.viewController.viewData);
						if (!found) return true;
					});
					return found;
				}(destinationObjectID));
				
				if (!viewData) {
					console.warn("The binding's destination could not be found.", destinationObjectID);
					continue;
				}
				
				var proto = this.prototypeFromData(viewData);
				obj = proto;
			}
			if (this.controllerShouldObserveObject(obj)) {

				var path = this.codePathForProjectIDOrNil(destinationObjectID);
				if (this.implementationHasObservable(obj)) {
					path += '.observable';
				}

				lines.push('\t['+path+' addObserver:self];');
			}
		}
		return lines.join('\n');};
	

iOSAppGenerator.prototype.generateRemoveObserverCode = function iOSAppGenerator__generateRemoveObserverCode(dict) {
		var lines = [];
		for (var destinationObjectID in dict) {

			var obj = _context.projectContext.connectableObjects[destinationObjectID];
			if (isKindOfType(obj, getType('appdoo.BasicDataSource'))) {
				lines.push('\t['+this.codePathForProjectIDOrNil(destinationObjectID)+' removeObserver:self];');
			}
		}
		
		
		
		return lines.join('\n');};
	
	
	
iOSAppGenerator.prototype.generateBindingsDictionaryCode = function iOSAppGenerator__generateBindingsDictionaryCode(dict) {

		var code = '@{\n';

		for (var destinationObjectID in dict) {
			
			var destinationCodePath = this.codePathForProjectIDOrNil(destinationObjectID);
			if(destinationCodePath == "nil" || destinationCodePath == "null" || destinationCodePath == "NULL") {
				continue;
			}
			code += '\t\t\t';
			code += '[NSNumber numberWithUnsignedInteger:['+destinationCodePath+' hash]]:\n';
			var __code = '			    @{\n';
			for (var destinationKeyPath in dict[destinationObjectID]) {
			
				
				var _ctr = 0;
				var _code = '';
				if (Array.isArray(dict[destinationObjectID][destinationKeyPath])) dict[destinationObjectID][destinationKeyPath].every(function (bindingInfo) {

					var codePath = this.codePathForProjectIDOrNil(bindingInfo.sourceObjectID);
					if (codePath === 'nil') {
						console.warn('generateBindingsDictionaryCode(): Failed getting codepath for binding source:', bindingInfo.sourceObjectID, bindingInfo);
						return true;
					}

					if (_ctr > 0) _code += '					},\n					@{\n';
					_code += '\t\t\t\t\t\t@"object": '+codePath+',\n';
					_code += '\t\t\t\t\t\t@"keyPath": @"'+bindingInfo.sourceObjectKeyPath+'",\n';
					if (bindingInfo.transformer)
						_code += '\t\t\t\t\t\t@"transformer": @"'+bindingInfo.transformer+'",\n';
					_ctr++;return true; }, this);
				
				if (!_code) continue;
				
				__code += '\t\t\t\t\t@"'+destinationKeyPath+'": @[@{\n';
				__code += _code;
				__code += '\t\t\t\t\t}],\n';
			}
			__code += '				},\n';
			code += __code;
		}
		code += '\t\t}';
		return code;};
	
	
iOSAppGenerator.prototype.generateAppDelegateImplementationMethods = function iOSAppGenerator__generateAppDelegateImplementationMethods(objects, dict, data) {

		var hasGlobalBindings = dict && Object.keys(dict).length > 0;
		var hasGlobalConnections = !!this.connectionsInCode['AppDelegate'];

		var methods = {};
		
		if (hasGlobalConnections) {
			var connectionsCode = this.connectionsCodeForInfo(this.connectionsInCode['AppDelegate']);
			methods['setConnections'] = ('- (void)setConnections {\n'+connectionsCode+'}');
		}

		if (hasGlobalBindings) {
			this.demandPluginWithIdentifier('info.appdoo-mac.BindingsHandler');
			
			var bindingsDictionaryCode = this.generateBindingsDictionaryCode(dict);
			var addObserverCode = this.generateAddObserverCode(dict);
			this.implementationIvars['_bindings'] = 'NSDictionary *';
			methods['prepareForBindings'] = ('- (void)prepareForBindings {\n\n	if (!_bindings) _bindings = '+bindingsDictionaryCode+';\n\n'+addObserverCode+'\n}');
			methods['observeValueForKeyPath:ofObject:change:context:'] = ('- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id<BindingsKeyValueCoding>)object change:(NSDictionary *)change context:(void *)context {\n	[BindingsHandler applyBindings:_bindings forKeyPath:keyPath ofObject:object];\n'+'}');
			this.addIncludeHeaderForThingWithOriginalID('BindingsHandler.h','AppDelegateImplementation');

		}
		
		if (this.overwritesModalInterfaceOrientations) {
			methods['application:supportedInterfaceOrientationsForWindow:'] = ('- (\n\n#ifdef __IPHONE_9_0\nUIInterfaceOrientationMask\n#else\nNSUInteger\n#endif\n\n)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {\n	if (_currentSupportedInterfaceOrientations) return _currentSupportedInterfaceOrientations;\n	return _defaultSupportedInterfaceOrientations;\n}');
			this.implementationIvars['_defaultSupportedInterfaceOrientations'] = 'NSUInteger';
		}
		

		
		this.addMethodsForObjects(objects, methods);
		
		
		var allObjects = objects;
		var launchingCode = '';
		if (allObjects.length)
			launchingCode += '	[[NSBundle mainBundle] loadNibNamed:@"GlobalObjects" owner:self options:nil];';
		
		var hasGlobalConnections = !!this.connectionsInCode['AppDelegate'];
		if (hasGlobalConnections) {
			launchingCode += '\n	[self setConnections];';
		}

		var hasGlobalBindings = dict && Object.keys(dict).length > 0;
		if (hasGlobalBindings) {
			launchingCode += '\n	[self prepareForBindings];';
		}
		
		if (data.metadata.globalTintColor) {
			if (launchingCode) launchingCode += '\n\n';
			launchingCode += '	// This sets the tint color of the window to the global tint color.\n	if ([_window respondsToSelector:@selector(setTintColor:)])\n		_window.tintColor = '+this.UIColorFromCSSColor(data.metadata.globalTintColor)+';\n';
		}
		
		if (this.overwritesModalInterfaceOrientations) {
			launchingCode += '\n\n	NSArray * supportedOrientations = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"];\n	for (NSString * interfaceOrientation in supportedOrientations) {\n		if ([interfaceOrientation isEqualToString:@"UIInterfaceOrientationLandscapeLeft"])\n			_defaultSupportedInterfaceOrientations |= UIInterfaceOrientationMaskLandscapeLeft;\n		else if ([interfaceOrientation isEqualToString:@"UIInterfaceOrientationLandscapeRight"])\n			_defaultSupportedInterfaceOrientations |= UIInterfaceOrientationMaskLandscapeRight;\n		else if ([interfaceOrientation isEqualToString:@"UIInterfaceOrientationPortrait"])\n			_defaultSupportedInterfaceOrientations |= UIInterfaceOrientationMaskPortrait;\n		else if ([interfaceOrientation isEqualToString:@"UIInterfaceOrientationPortraitUpsideDown"])\n			_defaultSupportedInterfaceOrientations |= UIInterfaceOrientationMaskPortraitUpsideDown;\n	}\n';
		}







		
		if (data.usesCustomNavigationBarFont && data.navigationBarFont) {
			launchingCode += '\n	[[UINavigationBar appearance] setTitleTextAttributes:@{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   NSFontAttributeName: [UIFont fontWithName:@"'+realIOSFont(data.navigationBarFont.fontName)+'" size:'+data.navigationBarFont.pointSize+'],\n';
			if (data.navigationBarLabelColor)
				launchingCode += '\t\t\t\t\t\t\t\t\t\t\t\t\t\t   NSForegroundColorAttributeName: '+this.UIColorFromCSSColor(data.navigationBarLabelColor);
			launchingCode += '\n\
														   }];\n';
		}
		if (data.usesCustomBarButtonItemFont && data.barButtonItemFont) {
			launchingCode += '\n	[[UIBarButtonItem appearance] setTitleTextAttributes:@{\n\
														   NSFontAttributeName: [UIFont fontWithName:@"'+realIOSFont(data.barButtonItemFont.fontName)+'" size:'+data.barButtonItemFont.pointSize+']\n\
														   } forState:UIControlStateNormal];\n';
		}
		if (data.usesCustomTabBarItemFont && data.tabBarItemFont) {
			launchingCode += '\n	[[UITabBarItem appearance] setTitleTextAttributes:@{\n\
														   NSFontAttributeName: [UIFont fontWithName:@"'+realIOSFont(data.tabBarItemFont.fontName)+'" size:'+data.tabBarItemFont.pointSize+']\n\
														   } forState:UIControlStateNormal];\n';
		}
		if (data.tabBarController && data.tabBarController.tabBar.tintColor) {
			launchingCode += '\n	[[UITabBar appearance] setTintColor:'+this.UIColorFromCSSColor(data.tabBarController.tabBar.tintColor)+'];\n';
		}
		methods['application:didFinishLaunchingWithOptions:'] = ('- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {\n'+launchingCode+'\n\treturn YES;\n}');
		
		if (this.appDelegateCode) {
			for (var selectorName in this.appDelegateCode) {
				if (!methods[selectorName]) {
					if (selectorName === 'application:didRegisterForRemoteNotificationsWithDeviceToken:') {
						methods[selectorName] = '- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {\n}';
					}
					else if (selectorName === 'application:didReceiveRemoteNotification:') {
						methods[selectorName] = '- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {\n}';
					}
					else if (selectorName === 'application:didFailToRegisterForRemoteNotificationsWithError:') {
						methods[selectorName] = '- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {\n}';
					}
					else continue;
				}
				var offset = 1;
				if (selectorName === 'application:didFinishLaunchingWithOptions:') offset = 14;
				methods[selectorName] = methods[selectorName].substr(0, methods[selectorName].length-offset)+this.appDelegateCode[selectorName].join('\n')+'\n'+methods[selectorName].substr(methods[selectorName].length-offset);
			}
		}
		
		var shouldSupportBackgroundAudio = true;
		if (shouldSupportBackgroundAudio) {
			methods['remoteControlReceivedWithEvent:'] = '- (void)remoteControlReceivedWithEvent:(UIEvent *)event {\n\t[[NSNotificationCenter defaultCenter] postNotificationName:@"RemoteControlEventReceived" object:event];\n}';
		}
		
		return this.generateStringFromMethods(methods);
};
	
	
iOSAppGenerator.prototype.connectionsCodeForInfo = function iOSAppGenerator__connectionsCodeForInfo(connectionsInCode) {
		var connectionsCode = '';
			if (Array.isArray(connectionsInCode)) connectionsInCode.every(function (info) {
				var codePath = this.codePathForProjectIDOrNil(info.sourceCID);
				if (codePath != 'nil') {
					switch (info.connectionType) {
						case 'outlet':
							connectionsCode += '	'+codePath+'.'+info.info.property+' = '+this.codePathForProjectIDOrNil(info.destinationCID)+';\n';
							break;
						case 'outletCollection':
							connectionsCode += '	['+codePath+'.'+info.info.property+' addObject:'+this.codePathForProjectIDOrNil(info.destinationCID)+'];\n';
							break;
						case 'action':
							connectionsCode += '	['+codePath+' addTarget:'+this.codePathForProjectIDOrNil(info.destinationCID)+' action:@selector('+info.info.selector+') forControlEvents:UIControlEvent'+ucfirst(info.info.eventType)+'];\n';
							break;
						case 'customAction':
							connectionsCode += '	['+codePath+' addTarget:'+this.codePathForProjectIDOrNil(info.destinationCID)+' action:@selector('+info.info.selector+') forEvents:@"'+info.info.eventType+'"];\n';
							break;
					}
				}return true; }, this);
			
		return connectionsCode;};
	

iOSAppGenerator.prototype.unconnectionsCodeForInfo = function iOSAppGenerator__unconnectionsCodeForInfo(connectionsInCode) {
		var connectionsCode = '';
			if (Array.isArray(connectionsInCode)) connectionsInCode.every(function (info) {
				var codePath = this.codePathForProjectIDOrNil(info.sourceCID);
				if (codePath != 'nil') {
					switch (info.connectionType) {
						case 'outlet':
							connectionsCode += '	'+codePath+'.'+info.info.property+' = nil;\n';
							break;
						case 'outletCollection':
							break;
						case 'action':
							connectionsCode += '	['+codePath+' removeTarget:'+this.codePathForProjectIDOrNil(info.destinationCID)+'];\n';
							break;
						case 'customAction':
							connectionsCode += '	['+codePath+' removeTarget:'+this.codePathForProjectIDOrNil(info.destinationCID)+'];\n';
							break;
					}
				}return true; }, this);
			
		return connectionsCode;};
	

iOSAppGenerator.prototype.generateImplementationMethods = function iOSAppGenerator__generateImplementationMethods(viewControllerData) {

		var scene = viewControllerData.sourceSceneData;
		var parentClass = this.parentViewControllerClassForEmbeddedScene[scene.$id];
		var sceneIsEmbedded = parentClass !== undefined;
		var embeddedViewControllers = this.embeddedViewControllersInViewControllerCID[scene.viewController.$id];
		var hasEmbeddedViewControllers = embeddedViewControllers && embeddedViewControllers.length;

		var sceneHasNavigationBar = !sceneIsEmbedded;
		
		var sceneHasACellBasedView = this.sceneHasASubviewThatMatchesConstraint(scene, function (subview) {
			return subview.$type === 'UITableView' ||
				   subview.$type === 'UICollectionView';
		});
		var dict = this.generateBindingsDictionaryForScene(scene);
		var sceneHasBindings = dict && Object.keys(dict).length > 0;
		var sceneHasSegues = scene.segues && scene.segues.length > 0;
		var methods = {};

		if (hasEmbeddedViewControllers) {
			var i = 1;
			if (Array.isArray(embeddedViewControllers)) embeddedViewControllers.every(function (className) {
				var methodName = 'embeddedViewController';
				if (i > 1) methodName += i;
				methods[methodName] = ('- ('+className+' *)'+methodName+' {\n	return ('+className+' *)self.childViewControllers[0];\n}');
				i++;return true; }, this);
			
		}
		
		if (sceneIsEmbedded) {
			methods['embeddingViewController'] = ('- ('+parentClass+' *)embeddingViewController {\n	return ('+parentClass+' *)self.parentViewController;\n}');
		}
		
		var connectionsInCode = this.connectionsInCode[viewControllerData.originalData.$id];
		var sceneNeedsCodeConnections = connectionsInCode && connectionsInCode.length;
		
		if (sceneNeedsCodeConnections) {
			if (sceneIsEmbedded) methods['viewDidLoad'] = ('- (void)viewDidLoad {\n	[super viewDidLoad];\n'+(sceneNeedsCodeConnections?'	[self performSelector:@selector(setConnections) withObject:nil afterDelay:0.0];\n':'')+'}');

			else methods['viewDidLoad'] = ('- (void)viewDidLoad {\n	[super viewDidLoad];\n'+(sceneNeedsCodeConnections?'	[self setConnections];\n':'')+'}');
		}
		
		if (sceneNeedsCodeConnections) {
			var connectionsCode = this.connectionsCodeForInfo(connectionsInCode);
			methods['setConnections'] = ('- (void)setConnections {\n'+connectionsCode+'}');

			var unconnectionsCode = this.unconnectionsCodeForInfo(connectionsInCode);
			methods['unsetConnections'] = ('- (void)unsetConnections {\n'+unconnectionsCode+'}');
		}


		if (sceneHasACellBasedView) this.demandPluginWithIdentifier('info.appdoo-mac.UIViewControllerSharedMethods');

		if (true) {
			var instructions = ['[super viewWillAppear:animated];',];
			
			if (!sceneIsEmbedded && sceneHasACellBasedView) {
				this.addViewControllerImplementationCode(scene.viewController.$id, 'viewWillAppear:', ['	[UIViewControllerSharedMethods unselectAllCellsInView:self.view animated:animated];']);
			}
				
			if (!sceneIsEmbedded && sceneHasNavigationBar)
				instructions.push('[self configureNavigationBarAnimated:animated];');
				
			if (sceneHasBindings) {
				this.addViewControllerImplementationCode(scene.viewController.$id, 'viewWillAppear:', ['\t[self prepareForBindings];']);
			}

			methods['viewWillAppear:'] = '- (void)viewWillAppear:(BOOL)animated {\n	'+instructions.join('\n	')+'\n}';
			
		}

		var layoutCode = this.generateLayoutCode(viewControllerData);
		if (layoutCode) {
			methods['performLayout'] = '- (void)performLayout {\n'+layoutCode+'}';
			methods['viewDidLayoutSubviews'] = '- (void)viewDidLayoutSubviews {\n	[super viewDidLayoutSubviews];\n	[self performLayout];\n}';
		}
		
		if (sceneHasBindings) {
			this.demandPluginWithIdentifier('info.appdoo-mac.BindingsHandler');
			
			var bindingsDictionaryCode = this.generateBindingsDictionaryCode(dict);
			var addObserverCode = this.generateAddObserverCode(dict);
			this.implementationIvars['_bindings'] = 'NSDictionary *';
			methods['prepareForBindings:'] = ('- (void)prepareForBindings {\n\n	if (!_bindings) _bindings = '+bindingsDictionaryCode+';\n\n'+addObserverCode+'\n}');
			
			methods['observeValueForKeyPath:ofObject:change:context:'] = (function () {
				var str = '- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id<BindingsKeyValueCoding>)object change:(NSDictionary *)change context:(void *)context {\n	[BindingsHandler applyBindings:_bindings forKeyPath:keyPath ofObject:object];\n';
				if (layoutCode) str += '	[self performLayout];\n';
				str += this.generatePostBindingsCode(viewControllerData)+'}';
				return str;
			}.call(this));

			var removeObserverCode = this.generateRemoveObserverCode(dict);
			methods['viewDidDisappear'] = ('- (void)viewDidDisappear:(BOOL)animated {\n\t[super viewDidDisappear:animated];\n'+removeObserverCode+'\n}');
			
		}
		
		if (sceneHasNavigationBar) {
			var navigationBarConfigurationCode = this.generateNavigationBarConfigurationCode(scene);
			methods['configureNavigationBarAnimated:'] = ('- (void)configureNavigationBarAnimated:(BOOL)animated {\n'+navigationBarConfigurationCode+'\n}');
		}

		if (scene.statusBarIsVisible === false && !sceneIsEmbedded) {
			methods['prefersStatusBarHidden'] = ('- (BOOL)prefersStatusBarHidden {\n\treturn YES;\n}');
		} else if (this.hidesStatusBarOnLaunch && parseInt(this.hidesStatusBarOnLaunch) > 1) {
			methods['prefersStatusBarHidden'] = ('- (BOOL)prefersStatusBarHidden {\n\treturn YES;\n}');
		} else {
			methods['prefersStatusBarHidden'] = ('- (BOOL)prefersStatusBarHidden {\n\treturn NO;\n}');
		}
        if (scene.v_statusBarIsBright) {
            methods['preferredStatusBarStyle'] = ('- (UIStatusBarStyle)preferredStatusBarStyle {\n\treturn UIStatusBarStyleLightContent;\n}');
        } else {
            methods['preferredStatusBarStyle'] = ('- (UIStatusBarStyle)preferredStatusBarStyle {\n\t if (@available(iOS 13, *)) {return UIStatusBarStyleDarkContent;} else {return UIStatusBarStyleDefault;}\n}');
        }
		
		if (sceneHasSegues) {
			this.demandPluginWithIdentifier('info.appdoo-mac.UIViewControllerSharedMethods');
			methods['prepareForSegue:sender:'] = ('- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {\n\t[UIViewControllerSharedMethods prepareViewController:self forSegue:segue sender:sender];\n}');
		}

		if (scene.hasCustomInterfaceOrientations) {
			var mask = parseInt(scene.supportedInterfaceOrientations);
			if (mask) {
				methods['supportedInterfaceOrientations'] = ('- (NSUInteger)supportedInterfaceOrientations {\n	return '+mask+';\n}');
				if (this.overwritesModalInterfaceOrientations)
					methods['supportedModalInterfaceOrientations'] = ('- (NSUInteger)supportedModalInterfaceOrientations {\n	return '+mask+';\n}');
			}
		}


		var allObjects = this.allObjectsForScene(scene);
		this.addMethodsForObjects(allObjects, methods);
		
		if (1) {
			var deallocStatements = [];
			for (var cid in this.deallocMethodsByCID) {
				var codePath = this.codePathForProjectIDOrNil(cid);
				if (codePath === 'nil') continue;
				if (codePath.indexOf('.') !== codePath.lastIndexOf('.')) continue;
				if (codePath.indexOf('self.embeddingViewController') === 0) continue;
				deallocStatements.push('['+codePath+' '+this.deallocMethodsByCID[cid]+'];');
			}
			if (sceneNeedsCodeConnections) {
				deallocStatements.push('[self unsetConnections];');
			}
			if (deallocStatements.length)
				methods['dealloc'] = ('- (void)dealloc {\n\t'+deallocStatements.join('\n\t')+'\n}');
		}
		
		if (viewControllerData.originalData.$type === 'UITableViewController') {
			methods['tableView:willDisplayCell:forRowAtIndexPath:'] = ('- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {\n	if (cell.contentView.backgroundColor) {\n		cell.backgroundColor = cell.contentView.backgroundColor;\n		cell.contentView.opaque = NO;\n		cell.contentView.backgroundColor = nil;\n	}\n}');
		}

		function addMethodWithSelectorName(selectorName) {
			if (selectorName === 'viewWillAppear:') {
				methods[selectorName] = '- (void)viewWillAppear:(BOOL)animated {\n	[super viewWillAppear:animated];\n}';
			}
		}
		
		var implementationCode = this.implementationCode ? this.implementationCode[scene.viewController.$id] : {};
		for (var selectorName in implementationCode) {
			if (!methods[selectorName]) addMethodWithSelectorName(selectorName);
			if (methods[selectorName]) methods[selectorName] = methods[selectorName].substr(0, methods[selectorName].length-1)+implementationCode[selectorName].join('\n')+'\n}';
		}

		var result = this.generateStringFromMethods(methods);

		if (sceneIsEmbedded && result.indexOf('tableView:') !== -1) {
			result = '@dynamic tableView;\n\n'+result;
		}
		
		return result;};
	
	
iOSAppGenerator.prototype.generateStringFromMethods = function iOSAppGenerator__generateStringFromMethods(methods) {

		if (!Object.keys(methods).length) return '';

		var vals = Object.keys(methods).map(function (key) {
		    return methods[key];
		});

		return vals.join('\n\n')+'\n';
	};
	
	
iOSAppGenerator.prototype.addDeallocMethod = function iOSAppGenerator_addDeallocMethod(cid, methodName) {
		if (!this.deallocMethodsByCID) this.deallocMethodsByCID = {};
		this.deallocMethodsByCID[cid] = methodName;};
	

iOSAppGenerator.prototype.addMethodsForObjects = function iOSAppGenerator__addMethodsForObjects(objects, methods) {
		if (Array.isArray(objects)) objects.every(function (obj) {
			if (!obj.isProcedure) return true;
			
			var selectorName = this.storyboardTransformer.selectorNameForProcedureID(obj.$id);
			methods[selectorName] = ('- (IBAction)'+selectorName+'(id)sender {\n'+ this.codeForInstruction(obj) + '}');return true; }, this);
		
};
	
	
iOSAppGenerator.prototype.codeForInstruction = function iOSAppGenerator__codeForInstruction(instruction) {
		var result = '';

		if (!instruction || instruction.enabled === false) return result;
		
		var proto = this.prototypeFromData(instruction);
		
		if (!proto) { console.warn('Type unknown: '+instruction.$type, instruction); return result; }
		if (!proto.transformDataForObjectiveC) {
			 console.warn('transformDataForObjectiveC() missing in '+instruction.$type, instruction); 
			return result;
		}
		
		result += '	'+proto.transformDataForObjectiveC(instruction, this)+'\n';

		if (Array.isArray(instruction.instructions)) instruction.instructions.every(function (_instruction) {
			result += this.codeForInstruction(_instruction);return true; }, this);
		
		
		return result;};
	

iOSAppGenerator.prototype.createProcedureFromData = function iOSAppGenerator_createProcedureFromData(PARAMETER_NOT_USED, actionInfo) {
		if (!actionInfo) { alertd('Missing actionInfo!'); return; }
		var actionType = actionInfo.actionType;
		
		var procedure;
		switch (actionType) {
			case 'showScene':
				if (!actionInfo || !actionInfo.destinationSceneID) return;
				procedure = createComponentFromDomain('ShowAnotherSceneInstruction', 'info.appdoo-mac', _context.projectContext, {
					targetSceneID: actionInfo.destinationSceneID,
					modalTransitionStyle: actionInfo.modalTransitionStyle,
					transfersDataAsInput: actionInfo.transfersDataAsInput,
					transferDataSourceID: actionInfo.transferDataSourceID
				});
				break;
			case 'navigateBack':
				procedure = createComponentFromDomain('NavigateBackInstruction', 'info.appdoo-mac', _context.projectContext,{});
				break;
			case 'objectAction':
				if (!actionInfo) return;
				if (!actionInfo.objectID) return;
				procedure = createComponentFromDomain('PerformSelectorInstruction', 'info.appdoo-mac', _context.projectContext,{
					objectID: actionInfo.objectID,
					selector: actionInfo.objectActionID,
					arguments: actionInfo.arguments,
					isCallingIBAction: actionInfo.isCallingIBAction
				});
				break;
		}
		return procedure;};
	

iOSAppGenerator.prototype.typeFromData = function iOSAppGenerator_typeFromData(data) {
		return typeFromData(data);};
	
	
iOSAppGenerator.prototype.prototypeFromData = function iOSAppGenerator_prototypeFromData(data) {
		return prototypeFromData(data);};
	
	
iOSAppGenerator.prototype.generateStringValueFromObjectProperty = function iOSAppGenerator__generateStringValueFromObjectProperty(object, property) {

		var binding = this.bindingForKey.call(object, property);
		if (binding) {
			return 'self.'+this.outletNameForProjectID[binding.destination]+'.'+binding.destinationKeyPath;
		}
		
		
		return this.ObjCStringify(object[property]);};
	
	
iOSAppGenerator.prototype.resourceNameForReferenceID = function iOSAppGenerator__resourceNameForReferenceID(referenceID) {
		var name;
		if (Array.isArray(this.resources)) this.resources.every(function (resource) {
			if (resource.referenceID === referenceID) {
				name = resource.name;
				return false;
			}return true; }, this);
		
		return name;};
	
	
iOSAppGenerator.prototype.registerInlineObject = function iOSAppGenerator_registerInlineObject(obj, originalScene) {
		if (!obj) return;
		
		if (!originalScene) {
			this.globalInlineObjects.push(obj);
			return;
		}

		if (!this.inlineObjectsForOriginalSceneID[originalScene.$id])
			this.inlineObjectsForOriginalSceneID[originalScene.$id] = [];
		
		this.inlineObjectsForOriginalSceneID[originalScene.$id].push(obj);
	};
	

iOSAppGenerator.prototype.registerInlineObjectForCellViewCID = function iOSAppGenerator_registerInlineObjectForCellViewCID(obj, cellViewCID) {
		if (!this.inlineObjectsForCellViewCID[cellViewCID])
			this.inlineObjectsForCellViewCID[cellViewCID] = [];
			
		this.inlineObjectsForCellViewCID[cellViewCID].push(obj);};
	
	
iOSAppGenerator.prototype.subviewWithID = function iOSAppGenerator__subviewWithID(id) {
		var result;
		if (Array.isArray(this.originalData.scenes)) this.originalData.scenes.every(function (scene) {
			if(scene.viewController.viewData.subviews) {
				if (Array.isArray(scene.viewController.viewData.subviews)) scene.viewController.viewData.subviews.every(function (subview) {
					if (subview.$id !== id) return true;
					result = subview;return true; }, this);
				
			}
			return false;return true; }, this);
		
		return result;};
	
	
iOSAppGenerator.prototype.globalObjectWithID = function iOSAppGenerator__globalObjectWithID(id) {
		var result;
		if (Array.isArray(this.originalData.objects)) this.originalData.objects.every(function (obj) {
			if (obj.$id !== id) return true;
			result = obj;
			return false;return true; }, this);
		
		
		if (!result)
		if (Array.isArray(this.globalInlineObjects)) this.globalInlineObjects.every(function (obj) {
			if (obj.$id !== id) return true;
			result = obj;
			return false;return true; }, this);
		

		return result;
	};
	

iOSAppGenerator.prototype.codePathForProjectIDOrNil = function iOSAppGenerator_codePathForProjectIDOrNil(id) {
		return this.codePathForProjectID(id) || 'nil';};
	
	
	
iOSAppGenerator.prototype.codePathForProjectID = function iOSAppGenerator_codePathForProjectID(id) {
		if (!id) {
			 console.warn('codePathForProjectID(): id is «'+id+'»!');
			 console.trace();
			return;
		}
		
		var self = this;
		var result = (function (id) {
		
			if (id === 'AppDelegate') {
				if (self.isTransformingGlobalObjects)
					return 'self';
				else {
					self.addIncludeHeaderForThing('AppDelegate.h');
					return '((AppDelegate *)(UIApplication.sharedApplication.delegate))';
				}
			}
		
			var globalObject = this.globalObjectWithID(id);
			if (globalObject) {
				if (self.isTransformingGlobalObjects)
					return 'self.'+this.outletNameForProjectID[id];
				else {
					this.addIncludeHeaderForThing('AppDelegate.h');
					return '((AppDelegate *)(UIApplication.sharedApplication.delegate)).'+this.outletNameForProjectID[id]+'';
				}
			}
			
			if (this.currentViewController) {

				if (id.indexOf('UINavigationBar') === 0) return 'self.navigationController.navigationBar';
				if (id.indexOf('UINavigationItem') === 0) return 'self.navigationItem';
	
				var currentSceneID = this.currentViewController.sourceSceneData.$id;
				var currentViewControllerID = this.currentViewController.originalData ? this.currentViewController.originalData.$id : '';
				
				if (currentViewControllerID === id) {
					return 'self';
				}
	
				if (this.parentViewControllerCIDForEmbeddedScene[currentSceneID] === id) {
					return 'self.embeddingViewController';
				}
				
				var theProperty = this.propertyForOriginalID[id];
				if (!theProperty) {
					console.warn('Missing p_roperty for',id, clone(this.propertyForOriginalID));
					return;
				}
				var outletViewControllerClassID = theProperty.classId;
				var outletViewControllerID = this.viewControllerByCodeIDs[outletViewControllerClassID];

				var outletName = this.outletNameForProjectID[id];
				if (!outletName) return;
				
				if (currentViewControllerID === outletViewControllerID) {
					return 'self.'+outletName;
				}
				
				var embeddedViewControllers = this.embeddedViewControllersInViewControllerCID[currentViewControllerID];
				
				if (embeddedViewControllers && embeddedViewControllers.indexOf(outletViewControllerClassID) !== -1) {
					var i = embeddedViewControllers.indexOf(outletViewControllerClassID);
					if (i > 0) return 'self.embeddedViewController'+(i+1)+'.'+outletName;
					else return 'self.embeddedViewController.'+outletName;
				}
		
				var parentClass = this.parentViewControllerClassForEmbeddedScene[currentSceneID];
				if (parentClass) {
					return 'self.embeddingViewController.'+outletName;
				}

			}
			
			if (this.currentCell) {
				var theProperty = this.propertyForOriginalID[id];
				if (theProperty) {
					if (this.currentCell.outletByOriginalID[id])
						return 'self.'+this.currentCell.outletByOriginalID[id].name;
					if (id.indexOf('ViewController') !== -1) return 'self.viewController';
					return 'self.viewController.'+theProperty.name;
				}
			}

			console.warn('No result for '+id+'. Property:',theProperty,'embeddedViewControllers:', embeddedViewControllers, 'outletViewControllerID:', outletViewControllerID, 'currentSceneID:',currentSceneID,'this.embeddedViewControllersInViewControllerCID',this.embeddedViewControllersInViewControllerCID);
			
		}.call(self,id));
		
		return result;};
	
	
iOSAppGenerator.prototype.generateOutletName = function iOSAppGenerator_generateOutletName(sourceData, proposedOutletName) {
	
		if (proposedOutletName) return proposedOutletName;
	
		var t = sourceData.$type||sourceData.constructor.name;
		
		if (t.indexOf('UI') === 0 ||
			t.indexOf('MK') === 0 ||
			t.indexOf('MP') === 0)
				t = t.substr(2);
		
		var i, c;
		for (i = 0, c = t.length; i < c; i++) {
			if (t[i].toLowerCase() === t[i]) {
				break;
			}
		}
		if (i === 1) {
			t = t[0].toLowerCase()+t.substr(1);
		}
		if (i > 1) {
			t = t.substr(0,i-1).toLowerCase()+t.substr(i-1);
		}

		t = this.generateCodeCompliantID(t);

		var outletName = t;
		
		if (!proposedOutletName && sourceData.bindings && sourceData.bindings.length) {
			var destinationKeyPath = sourceData.bindings[0].destinationKeyPath;
			if (destinationKeyPath !== 'contents') {
				if (destinationKeyPath && destinationKeyPath.indexOf('contents.') === 0) {
					destinationKeyPath = destinationKeyPath.substr(9);
				}
				var bindingTarget = CSymbolComformString(destinationKeyPath);
				
				if (outletName.indexOf('label') === 0)
					outletName += ucfirst(bindingTarget||'');
			}
		}
		
		return outletName;
	};
	
	
	
	
iOSAppGenerator.prototype.addCodeConnectionInVC_from__to__type__info__ = function iOSAppGenerator_addCodeConnectionInVC_from__to__type__info__(vcCID, sourceCID, destinationCID, connectionType, connectionInfo) {

		if (!this.connectionsInCode[vcCID]) this.connectionsInCode[vcCID] = [];

		this.connectionsInCode[vcCID].push({
			sourceCID: sourceCID,
			destinationCID: destinationCID,
			connectionType: connectionType,
			info: connectionInfo,
		});
};
	

iOSAppGenerator.prototype.addViewControllerImplementationCode = function iOSAppGenerator_addViewControllerImplementationCode(viewControllerCID, methodName, lines, position) {
	
		if (!this.implementationCode) this.implementationCode = {};
		if (!this.implementationCode[viewControllerCID]) this.implementationCode[viewControllerCID] = {};
		if (!this.implementationCode[viewControllerCID][methodName]) this.implementationCode[viewControllerCID][methodName] = [];

		function addValuesFromArray (a, pos) {
			if (!this) return a;
			if (!a) return this;
			if (pos === 0 || pos > 0) {
				if (Array.isArray(a)) a.every(function (v) {
					this.splice(pos, 0, v);
					pos++;return true; }, this);
				
			}
			else {
				if (Array.isArray(a)) a.every(function (v) {
					this.push(v);return true; }, this);
				
			}
		}
		
		addValuesFromArray.call(this.implementationCode[viewControllerCID][methodName], lines, position);};
	
	
iOSAppGenerator.prototype.registerAppDelegateCode = function iOSAppGenerator_registerAppDelegateCode(signature, code) {
		if (!this.appDelegateCode) {
			this.appDelegateCode = {};
		}
		if (!this.appDelegateCode[signature]) {
			this.appDelegateCode[signature] = [];
		}
		this.appDelegateCode[signature].push(code);};
	
	
iOSAppGenerator.prototype.expectedTypeForProperty = function iOSAppGenerator_expectedTypeForProperty(key) {
	if (key === "outletForOriginalID") return "";
	if (key === "outletNameForProjectID") return "";
	if (key === "keepPluginReferences") return "Boolean";
	if (__super) return __super.prototype.expectedTypeForProperty(key);
};

return iOSAppGenerator; }()));